Trying to add ids for anchor tag at the time of creating li tags

I have the following JS Fiddle working fine. Pasting the code here for reference:


<ul class="nav nav-tabs" id="test">
</ul>

var items=['a1','a2'];

var arrayLength = items.length;

for (var i = 0; i < arrayLength; i++) {
   
   $("#test").append("<li><a>"+items[i]+"</a></li>");
    
   
}

My requirement is to insert an id for the <a> tag and part of the id value will be coming from the the array values .

So, I would expect it to be like this inside the loop :

$("#test").append("<li><a id="tab_"+items[i]+">"+items[i]+"</a></li>");

And basically it would probably look something like this after inspecting the li element in the developer tools of chrome.

<li><a id="tab_a1">a1</a></li>
<li><a id ="tab_a2">a2</a></li>

But as soon as I try to define `id = tab_" it starts complaining. Am I doing something wrong?

You either have to escape the quotes or use single quotes for the string (or the attribute); also note that there’s a quote missing after the ID…

$("#test").append('<li><a id="tab_'+items[i]+'">'+items[i]+'</a></li>');
1 Like

Thanks !

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.