1

I have a variable with HTML in it. All I want to do is extract the last element of the node and click on it using pure vanilla JavaScript.

Here is what I have:

var rand = '
 <div class="readmorelink"> 
   <a href="example.com/link-to-follow/">
   Continue Reading        
   </a> 
 </div>';
5
  • So what have you tried so far? Commented Jan 23, 2017 at 12:46
  • 1
    var found = $(rand).filter(".readmorelink"); Commented Jan 23, 2017 at 12:46
  • I know how to do it jQuery but that needs to be in vanilla JS Commented Jan 23, 2017 at 12:48
  • See Parse a HTML String with JS Commented Jan 23, 2017 at 12:59
  • 1
    Why the downvotes ? Commented Jan 23, 2017 at 13:24

1 Answer 1

4

in Vanilla JS you can create a DOM element and set its innerHTML to the string you have, it will automatically reproduce the DOM structure inside :

// Don't forget to escape newlines
var rand = '<div class="readmorelink">\
    <a href="//example.com/link-to-follow/">Continue Reading</a>\
 </div>';
var elt = document.createElement('body');
elt.innerHTML = rand;
var links = elt.getElementsByTagName('a');
var target = links[links.length - 1];

// Target now equals the last 'a' element in the DOM tree

var clickEvent = new MouseEvent("click", {
    "view": window,
    "bubbles": true,
    "cancelable": false
});

target.dispatchEvent(clickEvent);
Sign up to request clarification or add additional context in comments.

2 Comments

while dispatchevent its redirecting. example.com/link-to-follow//example.com/link-to-follow
Yes because of the href attribute in the a element. If that href was //example.com/link-to-follow/ with 2 slashes before (as in the edited post) or with a specified protocol (ie: https) it would send you to example.com domain

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.