Set data attribute in jquery each loop

7.5k views Asked by At

I have a simple page:

<div>test 1</div>
<div>test 2</div>
<div>test 3</div>
<div>test 4</div>
<div>test 5</div>

the jQuery script:

$( document ).ready(function() {

    $.each($('div'), function (index, item) {
        $(item).data('testdata', index);
    });

});

Here is the jsfiddle: https://jsfiddle.net/yfo8m93g/

I loop through the div containers to add a data attribute to each one. However, when I inspect the page after running the fiddle, I do not see the data attributes in the DOM. What am I doing wrong?

1

There are 1 answers

5
Christopher Marshall On BEST ANSWER

Use .attr()

$( document ).ready(function() {

    $.each($('div'), function (index, item) {
        $(item).attr('data-testdata', index);
    });

});

https://jsfiddle.net/yfo8m93g/6/