How to use "For" instead of "every" function in jquery

Today I am very complicated with work and jQ. I got a morning for this, but I canโ€™t solve it :(. My work here:

<div class="container"> <p class="test">a</p> <div> <p class="test">a</p> </div> </div> 

In normal mode, I can use jQ with each for function to select all <p class="test">a</p> EX:

 $(".test").each(function() { $(this).text('a'); }); 

But I hear everyone say that the for function gets less timeload than the each function. Now I want to use for instead of each .. but I don't know how to write jQ code in this case.

Can anybody help me! many thanks!

+4
source share
5 answers

I would not worry about this if you did not repeat hundreds of them.

Cycle

for usually used with a regular DOM (aka without jQuery), for example ...

 var elements = document.getElementById('something').getElementsByTagName('a'); var elementsLength = elements.length; for (var i = 0; i < elementsLength; i++) { elements[i].style.color = 'red'; } 

Caching elementsLength is a good idea, so it doesn't count on every iteration. Thanks to the CMS for this suggestion in the comments.

Just adapt this for your jQuery object if you want to do this with jQuery.

Replace the elements variable with your jQuery collection, for example $('#something a') . I think you may need to reinstall the object if you need to do something else with jQuery.

+7
source

One thing you should pay attention to is that using an ordinal accessory as a result of choosing jQuery will return your own DomElement. If you want to use jQuery methods on them, you need to wrap them again:

 var testElements = $('.test'); for (var i = 0; i < testElements.length; i++) { // Using $() to re-wrap the element. $(testElements[i]).text('a'); } 

I would repeat what others said. If you are not dealing with many elements, this is a premature optimization. Repackaging elements to use the .text () method may even return it without any amplification at all.

+5
source

Have you tried the obvious solution?

 var nodes = $(".test"); for(var i = 0; i < nodes.length; i++) { var node = nodes[i]; } 
+1
source

This article shows that each() does not have a significant performance hit until you hit hundreds of thousands of looped items.

+1
source

Another alternative:

 for (var i = 0; i < $('.test').length; i++){ var element = $('.test').eq(i); } 
+1
source

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


All Articles