Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set data attribute in jquery each loop [duplicate]

Tags:

jquery

each

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?

like image 770
reggie Avatar asked Jan 09 '23 05:01

reggie


1 Answers

Use .attr()

$( document ).ready(function() {

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

});

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

like image 101
Christopher Marshall Avatar answered Jan 31 '23 14:01

Christopher Marshall