tags:

views:

45

answers:

2

I'm learning jQuery but I still don't fully undestand how it works. Suppose I have an unordered list like this:

<ul>
<li name="one">xxx</li>
<li name="two">xxx</li>
<li name="three">xxx</li>
</ul>

and I want to subsitute every line's text value with its name. Can you explain me why this works:

$('li').each(function() {
    $(this).text($(this).attr('name'));
});

while this one does not?

$('li').text($(this).attr('name'));
A: 

Because in the last example the iteration hapens inside the function. this doesn't reference to every single item, but what happens to be the current context.

That's why you have to iterate over every item.

Ikke
+4  A: 

They have completely different meaning.

In this:

$('li').each(function() {
    $(this).text($(this).attr('name'));
});
  • Select all the lis.
  • For each element found:
  • Change my (li) text to:
    • Pick my (li) attribute.

$('li').text($(this).attr('name'));

  • Select all the lis
  • Change their text to:
    • Pick my window's attribute name.

In the last example you apply the same text to all the li's to the name found in your window.

EDIT: for clarification: in the last example, $(this) refers to wherever the function you are executing belongs to. It can be window, or an object.

Alex Bagnolini
Thanks for your reply, just one more thing: with the second example `<li>`s are not displayed at all, shouldn't empty `<li>` items display at least the dots?
kemp
Don't worry about the second example. It's incorrect. I'm not sure why you're not getting the list marker (dot) with your empty li tags. You should be getting those, and the JQuery function isn't doing anything to prevent that. Without being able to see your complete html/javascript, though, it's difficult to say why.
MillsJROSS
Well the strange behavior in the second example is no big deal. I understood the point and that's what counts. Thanks Alex, accepting your clear and informative answer.
kemp