Find elements in jQuery document fragment using jQuery "find"

If I do the following, 0 and 2 returned:

 $html = $(document.createDocumentFragment()); $html.append('<a href="#">First link</a><a href="#">Second link</a>'); console.log($html.find('a').length); console.log($html[0].querySelectorAll('a').length); 

How can I make the jQuery method work as well? Therefore, basically, I want to be able to search for a document fragment using jQuery, instead of switching back and forth using the built-in JavaScript DOM functions.

+5
source share
2 answers

You need to pass the fragment of the string in jQuery and save the link to it:

 var $html = $(document.createDocumentFragment()); var $fragment = $('<a href="#">First link</a><a href="#">Second link</a>'); $html.append($fragment); console.log($fragment.filter('a').length); console.log($html[0].querySelectorAll('a').length); 

Then the analyzed fragment can be passed. Note that find here is replaced with filter , because we have a link to the collection of elements a , and find only works with children of the containing element.

This will result in logging 2 and 2 as expected. Demo: http://jsfiddle.net/fec9csxu/

0
source

Here it may help:

 var $html = $("html"); $html.append('<a href="#">First link</a><a href="#">Second link</a>'); console.log($html.find('a').length); console.log($html[0].querySelectorAll('a').length); 

Gives you the expected outputs 2 and 2.

-1
source

Source: https://habr.com/ru/post/1205485/


All Articles