nbg15 nbg15 - 1 month ago 8
Javascript Question

jquery: Change attribute value for all <li> List elements

I have a simple structure like:

HTML

<ul id="costsDropdown">
<li data-position="bla bla"></li>
</ul>


and I want to change each "data-position" attribute of my list Elements.

My first Jquery Shot was this here:

$("#costsDropdown ul").each(function() {
$("li").attr("data-position", "TEST-VALUE123");
});


but it doesnt work, I think my selector are wrong...

could anyone give me a hint please?

Thanks for any help!

Greetz

Answer

Your selectors are a bit off

$("#costsDropdown ul").each

That is trying to select the child ul of the container #costsDropdown (which is the ID of the ul) - what you want is:

$("#costsDropdown li").each(function() {
    $(this).attr("data-position", "TEST-VALUE123");
});

ID's are unique - no need to double up the selector with an ID and the type of element it is.

Note that I used $(this), not $("li"), inside the each callback. $("li") selects all li elements, anywhere on the page; we just want a jQuery wrapper for the one specific one we're handling inside the each.

In fact, the each is completely unnecessary because of the set-based nature of jQuery; if you use the .attr setter, it sets the attribute on all elements in the set:

$("#costsDropdown li").attr("data-position", "TEST-VALUE123");

That will set the value on all of the li elements inside #costsDropdown.

If you need to set separate individual values on the individual li elements, you still don't need each (though it's fine if you want to use it); you can use the version of attr that accepts a callback that it uses to find out what value to set:

$("#costsDropdown li").attr("data-position", function(index) {
    return "Test value " + index;
});

That will set "Test value 0" on the first li, "Test value 1" on the second, etc. And like the each example above, if you need to, you can use this within the callback to refer to the li for that call (possibly using $(this) to wrap it if you need a jQuery wrapper).

Comments