Home > Software design >  Issue setting .text in jQuery .each
Issue setting .text in jQuery .each

Time:05-26

So I'm trying to dynamically pass a list of nav bar items into an unordered list. The list as is follows (shortened for brevity).

i = 0
$('#navList li').each(function() {
  i  ;
  var name = menu[i].name;
  console.log(menu[i].name);

  $('a').text(name);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul  id="navList">
  <div >
    <div ></div>
    <div ></div>
  </div>
  <!-- **LISTITEMS** -->
  <li >
    <a  id="nav1" href="javascript:void(0);"><i ></i>Test1</a>
  </li>
  <li >
    <a  id="nav2" href="javascript:void(0);"><i ></i>Test2</a>
  </li>
</ul>

My two issues arise when

  1. as I iterate through my object of menu items, I can successfully console log the string text, but the jQuery .text function isn't working.

  2. Lastly, I'd also like to retain the I tag that contains my icon.

Thanks!

CodePudding user response:

You need to find the anchor inside the current li of the each loop - to do this, you can use the each loop parameters:

const menu = [{ name : 'test'}, {name:  'test 1'}];

$('#navList li').each(function(index, element) {    // change function to use parameters
  var name = menu[index].name;
  var $anchor = $(element).find('a');               // find the anchor in the current li
  
  $anchor.contents().filter(function() {
    return this.nodeType == 3;
  }).remove();                                      // remove current text
  
  $anchor.append(name);                             // append new text
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul  id="navList">
  <div >
    <div ></div>
    <div ></div>
  </div>
  <!-- **LISTITEMS** -->
  <li >
    <a  id="nav1" href="javascript:void(0);"><i >icon</i>Test1</a>
  </li>
  <li >
    <a  id="nav2" href="javascript:void(0);"><i >icon</i>Test2</a>
  </li>
</ul>

  • Related