How to get live DOM collections using jQuery?

How to access live DOM collections from jQuery?

Take, for example, this HTML <div id='a'></div> and this JavaScript code:

 var a = $('#a'); var divs = a[0].getElementsByTagName('DIV'); for(var i=0; divs.length < 20; ) { a.append($('<div>'+(i++)+'</div>')); } 

It will add 20 div children to <div id='a'> because divs are a live collection.

Is there anything in jQuery that I could replace the second line to get the same result?

var divs = $('#a div'); leads to an infinite loop.

JSFiddle is here .

+4
source share
6 answers

Each time, select an element, this will create a new jQuery object. I think this is the only way if the element changes.

 var a = $('#a'); for(var i=0; $('#a div').length < 20; ) { a.append($('<div>'+(i++)+'</div>')); if(i==50) break; } 

EDIT: Or this:

 for(var i=0, a=$('#a'); a.children('div').length < 20; ) { a.append($('<div>'+(i++)+'</div>')); if(i==50) break; } 

Or this, only one selector:

 var a = $('#a'); var length = a.children('div').length; while(length < 20) { a.append($('<div>'+(length++)+'</div>')); } 
+1
source

In case #a already contains divs:

 var $a = $('#a'), toAdd = Math.max(20 - $a.find('div').length, 0); for (var i = 0; i < toAdd; i++) { $a.append('<div>' + i + '</div>'); } 

This will be equivalent to the code above.

+2
source

Live collections are real, cannot be returned using modern jquery. In addition, a modern method that is intended to replace getElementsByTagName in the near future, getQuerySelectorAll also returns a static collection.

This is the answer to your question. Regarding the question that you really wanted to ask, other users have already tried to provide you some help.

+2
source

How to get live DOM collections using jQuery?

It's impossible.

This has the same effect as your sample code:

 var $a = $('#a'); for (var i = 0; i < 20; i++) { $a.append('<div>' + i + '</div>'); } 

http://jsfiddle.net/mathias/Af538/

Update: If you need to repeat the code periodically, you can use something like this:

 var $a = $('#a'), toAdd = Math.max(20 - $('div', $a).length, 0), i; for (i = 0; i < toAdd; i++) { $a.append('<div>' + i + '</div>'); } 

http://jsfiddle.net/mathias/S5C6n/

+1
source

Is it always 20 children?

Isn't it better to use the following

 var a = $('#a div'); for(var i=0; i < 20; i++) { a.append($('<div>'+(i)+'</div>')); } 
0
source

The syntax you are looking for is:

 var divs = $('div#a'); 

Since identifiers must be unique, you can simply do:

 var divs = $('#a'); 
0
source

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


All Articles