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?

3 Answers 3

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?

Sign up to request clarification or add additional context in comments.

2 Comments

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.
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.
2

Something like:

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.