Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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)

like image 668
Farzher Avatar asked May 04 '15 21:05

Farzher


People also ask

What is the type of the object that is returned by document querySelectorAll ()?

querySelectorAll() The Document method querySelectorAll() returns a static (not live) NodeList representing a list of the document's elements that match the specified group of selectors.

What can I use instead of document querySelector?

The other alternative is element. query / queryAll . These are alternative methods to querySelector and querySelectorAll that exist on DOM parent nodes. They also take selectors, except these selectors are interpreted relative to the element being queried from.

What does the querySelectorAll () method do?

The querySelectorAll() method in HTML is used to return a collection of an element's child elements that match a specified CSS selector(s), as a static NodeList object. The NodeList object represents a collection of nodes. The nodes can be accessed by index numbers. The index starts at 0.

What is the difference between document querySelector and document querySelectorAll?

Differences: As seen above, querySelector() methodcan only be used to access a single element while querySelectorAll() method can be used to access all elements which match with a specified CSS selector. To return all matches, querySelectorAll has to be used, while to return a single match, querySelector is used.


2 Answers

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'); 
like image 182
Madara's Ghost Avatar answered Oct 13 '22 22:10

Madara's Ghost


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') 
like image 34
Damian Krawczyk Avatar answered Oct 13 '22 21:10

Damian Krawczyk