0

I'm appending HTML code into a div, it's an unordered list. So first I do:

$('.placeholder').append('<ul>');

This works as expected. Then I do a loop for the list items:

$.each(headings, function(index, heading){
    $('.placeholder').append('<li>' + heading + '</li>');
})

Then append the closing ul tag

$('.placeholder').append('</ul>');

The problem is the code comes out like so:

<ul></ul>
<li></li>
<li></li>
<li></li>

Why is it appending the closing ul tag at the beginning of the each loop when the code is written so it appends it afterwards?

2
  • 2
    appending is NOT like building a string. You are creating a single element. You need to append the lis to the ul that you created. Commented Mar 2, 2018 at 14:38
  • $('.placeholder ul').append('<li>' + heading + '</li>'); and ditch $('.placeholder').append('</ul>'); Commented Mar 2, 2018 at 14:58

3 Answers 3

2

You don't need to do .append('</ul>');. .append('<ul>'); has already added the full ul node to the HTML.

Plus, you need to add your lis inside your ul, not inside .placeholder :

$.each(headings, function(index, heading){
    $('.placeholder ul').append('<li>' + heading + '</li>');
})
Sign up to request clarification or add additional context in comments.

Comments

1

Append both the starting and closing tag:

$('.placeholder').append('<ul></ul>');

Then append your <li>'s inside your <ul>:

$.each(headings, function(index, heading) {
    $('.placeholder ul').append('<li>' + heading + '</li>');
})

Comments

0

Use map instead to append them all at once, at the end.

var $ul = $('<ul>');

$ul.append(
  $.map(headings, function(element){
    return '<li>' + element + '</li>';
  })
);

$('.placeholder').append($ul);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.