Can jQuery find elements before adding them to a document?

I find that the HTML / DOM created with $ () is not searchable until it is added to the document. Is this expected, or am I doing something wrong?

var html = "<div data-test='test'>testdiv</div>"; // Convert HTML string to an orphaned JQ DOM object var dom = $(html); // Search orphaned DOM for element(s) with the specified attr var found1 = dom.find('[data-test]'); // --> found1.length == 0, why not 1? // Now insert the orphaned DOM into the document $('#content').html(dom); // And now JQ will find the desired elements var found2 = $('[data-test]'); // --> found2.length is 1, as expected 

Here is a demo: http://jsfiddle.net/5dVc8/

UPDATE

It turns out my initial question was too simplistic.

Answer

@RocketHazmat really dealt with what I originally asked, but when I went to use this information, I found that I was not specific enough.

Turns out I need to map the elements in the AND / OR root directory. It looks like, as @ RocketHazmat reports, .find () matches children, but .filter () only matches the root.

Here's an updated snippet and a new fiddle for demonstration:

 var html = "<div data-test='test1'>"; // Root html += "<div data-test='test2'></div>"; // Child html += "</div>"; // Convert HTML string to an orphaned JQ DOM object var dom = $(html); // Search orphaned DOM object for element(s) with the specified attr // (We'll find none) var found1 = dom.find('[data-test]'); $('#count1').html('count1='+found1.length+", val="+found1.attr('data-test')); // Search orphaned DOM object for element(s) with the specified attr // (We'll find none) var found2 = dom.filter('[data-test]'); $('#count2').html('count2='+found2.length+", val="+found2.attr('data-test')); // Now append the orphaned DOM to the document $('#content').html(dom); // And now JQ will find the desired elements var found3 = $('[data-test]'); $('#count3').html('count3='+found3.length); 

and updated script: http://jsfiddle.net/XyDSg/2/

+4
source share
2 answers

Try using .filter() instead of .find() .

 var found1 = dom.filter('[data-test]'); 

.find() searches for all children. In your case, '[data-test]' is the β€œroot” element, so you need .filter() .

UPDATE:

You can wrap your HTML in another <div> , then .find() will work the way you want.

 var dom = $('<div>'+html+'</div>'); var found1 = dom.find('[data-test]'); 

Remember to delete it when you add it to another location.

 $('#content').html(dom.html()); // This "removes" the parent `<div>` 
+7
source

You can create a div as a jQuery object

 var myDiv = jQuery('<div/>', { 'data-test' : 'test' }); 

And then add it anywhere, like

 $('#myElement').append(myDiv); 

The beauty of this is you can create a div and then manipulate it like any jquery object.

-one
source

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


All Articles