我有一个带有HTML的变量。我想要做的就是提取节点的最后一个元素,然后使用纯vanilla JavaScript单击它。
这就是我所拥有的:
var rand = '
<div class="readmorelink">
<a href="example.com/link-to-follow/">
Continue Reading
</a>
</div>';
答案 0 :(得分:3)
在Vanilla JS中你可以创建一个DOM元素并将其innerHTML设置为你拥有的字符串,它会自动重现内部的DOM结构:
// 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);