1

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])}
7
  • @RyanWilson I need an element of array, not the whole array to be in data-value Commented Jan 7, 2021 at 5:22
  • in your .forEach, the function parameter item is a single item of the array, that's why you get undefined by this item[index] Commented Jan 7, 2021 at 5:28
  • @RyanWilson arrayDescr.forEach(function(item, index){ $("#responseul").append("<li class='list-group-item'> Name: " + item + "</li>");}); this code works and creates every li with every element of array in order. but when i use item without [index] it gives me undefined and sets attribute value 3 Commented Jan 7, 2021 at 5:35
  • Great, does that mean you solved your own problem? Commented Jan 7, 2021 at 5:38
  • for some reason item working properly only when i append li, not when i set item as attribute value Commented Jan 7, 2021 at 5:40

3 Answers 3

1

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");
}
Sign up to request clarification or add additional context in comments.

1 Comment

Fighting the good fight: providing the OP with a real JavaScript answer; jQuery needs to be purged from Earth.
0

You can iterate li element and assign attr like below

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

Comments

0

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]);
});

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.