Sikander
Sikander

Reputation: 2835

Jquery accessing every list item by its index

I am following a beginner video tutorial for Jquery and just went through this code: (inside .ready() )

$('ul li ').each(function(e){

    $this().css{background' ,'red'}
    $this().append(e);

});

now e prints each li index , can someone please explain me how does it get index for each item as it's not a loop .

Upvotes: 0

Views: 132

Answers (2)

ntgCleaner
ntgCleaner

Reputation: 5985

Well, the .each() function is a loop. It almost literally says "For Each item that has the name 'ul li', do something."

The letter 'e' inside the parantheses is your actual index number. When you use an .each loop, the function gathers the number of whatever it's looking at and moves on until there are no more.

To simply show the number of the index, you can say:

$('ul li').each(function(i){  //I like to use the letter 'i' which more literally stands for 'index'
    console.log(i);
});

This will show in your console as:

0
1
2
3
4
5

Assuming you have six of those elements.

Now, your use of $this means nothing. When using it properly it's written as $(this) which means "this element" since we're in a function that goes through each list element, it will take the list element it is currently looking at, then do whatever you want.

If you'd like the background color to be red of all of your list elements (like it seems you want to do) you would write:

$('ul li').each(function(i){  
    $(this).css({"background": "red"});
});

I'm not sure what you're trying to do with the .append function. By doing this, you're literally adding a list element to your list element for every list element!

Can you explain what you are trying to accomplish?

UPDATE As your title says "Accessing every list item by its index," If you would like to access a particular list item, and not all of them, you can use the function .eq(). Let's say you have 6 list elements and you want the fourth one to have a red background. All you would have to do it this:

$('ul li').eq(3).css({"background":"red"});

Remember, index numbers start at zero, so the fourth one would be #3. (but of course, this would be faster and simpler in CSS!)

Upvotes: 2

Andrew
Andrew

Reputation: 20111

Actually, .each() is a loop/iterator. It will iterate over each of the elements that match. Eg: all the ul lis.

It will run through the code for every one it matches, and the DOM element will be accessible with $(this)

See the docs: http://api.jquery.com/jquery.each/

Upvotes: 1

Related Questions