user14337693
user14337693

Reputation: 27

JQuery - Set array element as attribute value for every <li>

I have an array arrayDescr and I need to use forEach to add to every <li> an attribute data-value. The value of data-value should be an arrayDescr element. For example I have three <li>'s and I have two arrayDescr elements. Two of three <li>'s should have attribute data-value arrayDescr[0], [1] and etc.

This code works but I need it to work in forEach:

$("#name1").attr("data-value", arrayDescr[0])

#name should be function(){return 'name' (i+1)}. In forEach this code returns undefined:

arrayDescr.forEach(function(item, index){
$("li").attr("data-value", item[index])}

Upvotes: 1

Views: 1283

Answers (3)

ZIASH
ZIASH

Reputation: 135

I think you should be iterating over li elements and set their attributes in the forEach like

$("li").each(function(i,item){
    if(arrayDescr.length > i)
        $(item).attr("data-value",arrayDescr[i]);
});

Upvotes: 0

anand shukla
anand shukla

Reputation: 706

You can iterate li element and assign attr like below

$( "li" ).each(function( index ) {
     if(index<arrayDescr.length){
       $( this ).attr("data-value", arrayDescr[index]) ;
   }
});

Upvotes: 0

BGPHiJACK
BGPHiJACK

Reputation: 1397

Here's a Vanilla Solution

var elem = document.querySelectorAll('li');

for (let i = 0; i < elem.length; i++) {
elem[i].setAttribute("data-value", "set value here, or determine how to make it dynamic"+i);
}

I haven't tested it on my end, but confident this should do what you want without JQuery and it be acceptable across many browsers (including mobile).

for (let i = 0; i < elem.length; i++) {
elem[i].setAttribute("data-value", (YourDescArray[i] !== undefined)?YourDescArray[i]:"problem");
}

Upvotes: 1

Related Questions