Question

Hey all I am trying to find all data attributes and replace the name with a number count.

The example HTML is this:

<li class="ui-menu-item" role="presentation" data-name="0">
  <a id="ui-id-2" class="ui-corner-all" tabindex="-1">AScript</a>
</li>

<li class="ui-menu-item" role="presentation" data-name="0">
  <a id="ui-id-2" class="ui-corner-all" tabindex="-1">Something</a>
</li>

etc etc...

There are about 20 or so with that same data-name attribute. I am wanting to loop through the page, finding that attribute, and then replacing that number and adding the correct number to it.

As an example:

<li class="ui-menu-item" role="presentation" data-name="0">
  <a id="ui-id-2" class="ui-corner-all" tabindex="-1">AScript</a>
</li>

<li class="ui-menu-item" role="presentation" data-name="1">
  <a id="ui-id-2" class="ui-corner-all" tabindex="-1">Something</a>
</li>

<li class="ui-menu-item" role="presentation" data-name="2">
  <a id="ui-id-2" class="ui-corner-all" tabindex="-1">Hey there</a>
</li>

etc etc...

Notice how data-name is 0, 1, 2, etc etc.

That is what i am looking to do. Is that possible using jQuery?

Was it helpful?

Solution

You can loop through any element with a certain property and then change that element, like in the example below:

$('[data-name]').each(function (e) {
    // Set the data-name to the item number
    $(this).attr('data-name', e);

    // Print the new `data-name` to the console
    console.log($(this).attr('data-name'));
});

JSFiddle: http://jsfiddle.net/g2tpJ/5/

Note: Take a look at this post to decide on using attr or data: jQuery Data vs Attr?

OTHER TIPS

Something like:

$("[data-name=0]").each(function(i) {
    $(this).data("name", i);
});

First select all li tags who have an attribute called data-name, and with a loop, change it's value.

$('li[data-name]').each(function(i) {
    $(this).attr('data-name',  i);
});

Edited: thought you only want to add a number to the end of the attribute.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top