how to dynamically change the href attribute with the array of id’s?

Tags: , ,



I have these elements and I want to change the id’s dynamically using the fetched id array via server which I have categories (Ex: ["category 1", "category 2","category 3","category 4","category 5", "category 6"]). I don’t know how to do this nothing seems to work.

<li role="presentation" class="active categories"><a href="#all" aria-controls="all" role="tab" data-toggle="tab">ALL</a></li>
                <li role="presentation" class="categories"><a href="#chicken" aria-controls="chicken" role="tab" data-toggle="tab">CHICKEN</a></li>
                <li role="presentation" class="categories"><a href="#fish" aria-controls="fish" role="tab" data-toggle="tab">FISH</a></li>
                <li role="presentation" class="categories"><a href="#turkey" aria-controls="turkey" role="tab" data-toggle="tab">TURKEY</a></li>
                <li role="presentation" class="categories"><a href="#miscellenous" aria-controls="miscellenous" role="tab" data-toggle="tab">MISCELLANOUS</a></li>
                <li role="presentation" class="categories"><a href="#frozen" aria-

Answer

`So, from your question, I understand that you want to give each of the elements the id with the value in the fetched array.

So for the first <li> element, the id would be category 1. If this is what you are asking for, the solution is to grab the required elements

<div id="parent">
    <ul>
      <li role="presentation" class="active categories"><a href="#all" aria-controls="all" role="tab" data-toggle="tab">ALL</a></li>
      <li role="presentation" class="categories"><a href="#chicken" aria-controls="chicken" role="tab" data-toggle="tab">CHICKEN</a></li>
      <li role="presentation" class="categories"><a href="#fish" aria-controls="fish" role="tab" data-toggle="tab">FISH</a></li>
      <li role="presentation" class="categories"><a href="#turkey" aria-controls="turkey" role="tab" data-toggle="tab">TURKEY</a></li>
      <li role="presentation" class="categories"><a href="#miscellenous" aria-controls="miscellenous" role="tab" data-toggle="tab">MISCELLANOUS</a></li>
      <li role="presentation" class="categories"><a href="#frozen" aria-controls="last" role="tab" data-toggle="tab">LAST</a></li>
    </ul>
  </div>




let fetchedArray = ['cat1','cat2','cat3','cat4','cat5','cat6'];
    $('li').each((i,el) => {
      $(el).attr('id',fetchedArray[i]);
    })


Source: stackoverflow