How to execute document.querySelectorAll on a text string without inserting it into DOM

拜拜、爱过 提交于 2020-12-24 15:21:12

问题


var html = '<p>sup</p>'

I want to run document.querySelectorAll('p') on that text without inserting it into the dom.

In jQuery you can do $(html).find('p')

If it's not possible, what's the cleanest way to to do a temporary insert making sure it doesn't interfere with anything. then only query that element. then remove it.

(I'm doing ajax requests and trying to parse the returned html)


回答1:


With IE 10 and above, you can use the DOM Parser object to parse DOM directly from HTML.

var parser = new DOMParser();
var doc = parser.parseFromString(html, "text/html");
var paragraphs = doc.querySelectorAll('p');



回答2:


You can create temporary element, append html to it and run querySelectorAll

var element = document.createElement('div');
element.insertAdjacentHTML('beforeend', '<p>sup</p>');
element.querySelectorAll('p')


来源:https://stackoverflow.com/questions/30040319/how-to-execute-document-queryselectorall-on-a-text-string-without-inserting-it-i

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!