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

后端 未结 2 943
孤独总比滥情好
孤独总比滥情好 2020-12-30 23:45
var html = \'

sup

\'

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

相关标签:
2条回答
  • 2020-12-31 00:19

    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');
    
    0 讨论(0)
  • 2020-12-31 00:36

    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')
    
    0 讨论(0)
提交回复
热议问题