James
James

Reputation: 1572

Using for instead of .each()

My assumptions are the .each() function is slower than a for loop when dealing with a lot of elements.

My problem is with the for loop i'm unable to manipulate the elements as i'm looping through them. I can do this fine with .each(). This could be a simple answer.

Javascript:

var element = $('#element h3');
var length = element.length;
var newHtml;

for(i=0;i<length;i++){

  newHtml = element[i].html();

  ...test newHtml
}

The code breaks when I try to grab the .html() of the element. I've seen posts that explain this is the way to loop through elements with a for loop, but grabbing information from them and manipulating them was never addressed.

Any help will be much appreciated!

Upvotes: 1

Views: 326

Answers (3)

Muhammad Bekette
Muhammad Bekette

Reputation: 1434

you are mixing jQuery with javascript like in element[i].html(); your code should be like this

function myfunction(){
    var element = document.getElementsByName('element');
    var length = element.length;
    var newHtml;
    for(i=0;i<length;i++){
        newHtml = element[i].innerHTML;
    }
}

note that document.getElementById() only return one result so you have to put "element" in name attr. and frankly .each is way easier

Upvotes: 0

sabithpocker
sabithpocker

Reputation: 15566

If you are looking for an over optimized solution to handle huge amounts of h3 in a single stretch, forget jquery.

var element = document.getElementById('element');
var headings = element.getElementsByTagName('h3');
var length = headings.length;
var newHtml;

for(i=0;i<length;i++){

  newHtml = headings[i].innerHTML;

  ...test newHtml
}

Upvotes: 0

SLaks
SLaks

Reputation: 887413

element[i] is a raw DOM element, not a jQuery object. (just like this in .each())

You want element.eq(i), which will return a jQuery object wrapping the ith element.

Upvotes: 6

Related Questions