jQuery append not displaying html with each method

Viewed 155

I have a list of elements.

<ul>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
</ul>

  $(function() {
    var liNodes = $("li");
    liNodes.each(function(index, value) {
      var span = $("<span></span>");
      value.append(span);
      console.log(value);
    });
  });

I want to iterate over the li elements, appending a span class to each but instead it displays this:

  • One[object Object]
  • Two[object Object]
  • Three[object Object]

What am I doing wrong here? thank you

3 Answers

The issue is because value is an Element object, not a jQuery object, so you're calling the native append() method, not the jQuery one. To fix this either convert value to a jQuery object first:

$(function() {
  var liNodes = $("li");
  liNodes.each(function(index, value) {
    var span = $("<span>Foo</span>");
    $(value).append(span);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
</ul>

Or create the span Element object and use appendChild() on value:

$(function() {
  var liNodes = $("li");
  liNodes.each(function(index, value) {
    var span = document.createElement('span');
    span.innerText = 'Foo';
    value.appendChild(span);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
</ul>

With all that said, note that if you want to create an identical element in all li, then you don't need a loop at all, it's a one-liner:

$('li').append('<span>Foo</span>');

Hope this helps

    var liNodes = $("li");
    liNodes.each(function(index, value) {
      //var span = $("<span></span>");
      let span = document.createElement("span");
      value.append(span);
      console.log(value);
    });
  });

You can play around Here

Just one line of change in your code everything else works fine.

  var liNodes = $("li");
    liNodes.each(function(index, value) {
        var span = "<span>Foo</span>";
        $(value).append(span);
        console.log(value);
    });

Related