简体   繁体   中英

How to get an HTML element from a string with vanilla JS

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>';

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM