Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to using "For" instead of "each" function in jquery

Today i'm very stack with a Work and jQ. I was get a morning for it but i can't resolve it :(. My Work here:

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

In normal, i can using jQ with each function for select all <p class="test">a</p> EX:

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

But i hear everyone talk that, for function get a less timeload than each function. Now i want using for instead of each.. but i don't know how to write code jQ in this case.

Somebody can help me!. thankyou!

like image 778
Rueta Avatar asked Dec 08 '22 02:12

Rueta


1 Answers

I wouldn't worry about it unless you were iterating through hundreds of them.

for loop is usually used with normal DOM (aka without jQuery) traversing, like...

var elements = document.getElementById('something').getElementsByTagName('a');

var elementsLength = elements.length;

for (var i = 0; i < elementsLength; i++) {

    elements[i].style.color = 'red';
}

Caching of elementsLength is a good idea so it is not calculated every iteration. Thanks to CMS for this suggestion in the comments.

Just adapt that for your jQuery object if you wanted to do it with jQuery.

Replace elements variable with your jQuery collection, like $('#something a'). I think you may need to rewrap the object if you need to do any more jQuery stuff with it.

like image 76
alex Avatar answered Dec 21 '22 21:12

alex