0

Why is it that, whichever of the following I use to create a new <ul> element, the HTML is empty:

var complaintsList = $('<ul/>', { id : 'myId' });

or

var complaintsList = $("<ul id='myId'></ul>");

alert($(complaintsList).html());

When I add <li> elements to the list and output the HTML, only the HTML of the <li> elements is displayed.

Can someone explain what I'm doing wrong please?

Jason Evans
  • 28,906
  • 14
  • 90
  • 154

3 Answers3

2

In the console:

var complaintsList = $('<ul/>', { id : 'myId' });

complaintsList
[
<ul id=​"myId">​</ul>​
]

complaintsList.html()
""

complaintsList.append("<li>")
[
<ul id=​"myId">​
<li>​</li>​
</ul>​
]

complaintsList.html()
"<li></li>"

It works as expected. The html of the ul is blank because there is nothing in it. Once you add the li, there is a list item in it.

.html() only gives you the HTML of the contents of the element. So when you have nothing in the element, the HTML will be an empty string. If you need to get the outerHTML of the element, you can use the jQuery outerHTML plugin.

sachleen
  • 30,730
  • 8
  • 78
  • 73
  • This is so weird - even after populating the list with li elements, and dumping the HTML to console.log, the ul element is not part of the HTML? – Jason Evans Jun 29 '12 at 16:30
  • No, it'll only give you the HTML of the contents of the element, not including the element. – sachleen Jun 29 '12 at 16:38
  • Yup I see I've got the wrong idea here - I've asked a very silly question indeed :) Thanks guys for putting me straight - been one of those days! – Jason Evans Jun 30 '12 at 08:22
0

http://api.jquery.com/html/ says:

"Get the HTML contents of the first element in the set of matched elements."

.html() returns only the internal contents of the element, but not the element itself.

See innerHTML vs outerHTML, .html() is similar to the .innerHTML property.

biziclop
  • 14,466
  • 3
  • 49
  • 65
0

Why is it that, whichever of the following I use to create a new element, the HTML is empty

Because the html method returns the HTML code of the elements inside the (first) element in the jQuery object.

Can someone explain what I'm doing wrong please?

You have assumed that the html method also includes the HTML code of the element in the jQuery object.


Side note: The variable complaintsList already contains a jQuery object, so you don't have to wrap it in another jQuery object to use jQuery methods on it:

alert(complaintsList.html());
Guffa
  • 687,336
  • 108
  • 737
  • 1,005