1

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?

StealthRT
  • 10,108
  • 40
  • 183
  • 342

3 Answers3

2

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?

Community
  • 1
  • 1
Mark
  • 2,184
  • 1
  • 16
  • 28
  • I don't think that would work. All the data-name's start out with "0". i am needing to change that to a unique number for each one it finds. – StealthRT Mar 21 '14 at 13:51
  • Ahh in that case you can replace the `$(this).attr('data-name', $(this).attr('data-name') + 'N');` line with `$(this).attr('data-name', e);`. Edited my original post. – Mark Mar 21 '14 at 13:58
2

Something like:

$("[data-name=0]").each(function(i) {
    $(this).data("name", i);
});
tymeJV
  • 103,943
  • 14
  • 161
  • 157
1

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.

Entropyk
  • 117
  • 4