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>';
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
CodyMan
  • 153
  • 7
  • 21

1 Answers1

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);
Mouradif
  • 2,666
  • 1
  • 20
  • 37
  • 1
    while dispatchevent its redirecting. http://example.com/link-to-follow//example.com/link-to-follow/ – CodyMan Jan 23 '17 at 13:08
  • 1
    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 – Mouradif Jan 23 '17 at 13:14