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

Time:10-07

I have the following JS Fiddle https://jsfiddle.net/73rpubfd/ 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 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?

CodePudding user response:

I think it's an issue with the format of the html props needing double quotes. The best way to create complex strings is to use template literals like so:

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

CodePudding user response:

Using Template literals can contain placeholders indicated by ${expression} and useful for string interpolation

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

var arrayLength = items.length;

for (var i = 0; i < arrayLength; i  ) {
   const li = `<li><a id="tab_${items[i]}">${items[i]}</a></li>`;
   $("#test").append(li);
   
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

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

Or in one line and without jQuery

Use array map method and transform each array item to li html and lastly join by empty.

const html = items.map(item => `<li><a id="tab_${item}">${item}</a></li>`).join('');

$("#test").append(html);

CodePudding user response:

You need to escape the double quotes if they appear within another quotes.

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

The other solution is to use backticks:

$("#test").append(`<li><a id="tab_">${items[i]}</a></li>`);
  • Related