1

http://jsfiddle.net/uGyTB/

var s = $("<li><a href='index.html'><h3>hello</h3></a></li>");
alert(s.html());​

Shows that the li element is not being created. Why?

hunterp
  • 15,716
  • 18
  • 63
  • 115

2 Answers2

8

The s is the <li> element. Its inner HTML is what you're fetching with .html().

You can prove this with: alert(s.get(0).tagName);​

Brad
  • 159,648
  • 54
  • 349
  • 530
  • But I already have a UL, And I need to create many LI. Are you saying the UL is ignored?? I'm using: s.appendTo(listSelector); – hunterp Dec 16 '12 at 21:50
  • Also you may find that there will be issues ith your structure. A `h3` is not supposed to be inside an `a`. – prodigitalson Dec 16 '12 at 21:51
  • @hunterp, No, nothing is ignored. When you create an element with jQuery, the element returned is the element you just created. You can still append it to a `
      `.
    – Brad Dec 16 '12 at 21:51
  • @hunterp: no hes saying that `.html()` is going to give you the CONTENT of the `li` not the `li` itself. – prodigitalson Dec 16 '12 at 21:52
  • I've updated the jsFiddle with the full example: http://jsfiddle.net/uGyTB/1/ You can see that the list is created incorrectly. Why? – hunterp Dec 16 '12 at 21:55
  • @hunterp it wouldn't append if it wasn't an LI since it would be invalid HTML – charlietfl Dec 16 '12 at 21:57
  • try: `alert($('
      ').append(s).html());​`
    – charlietfl Dec 16 '12 at 21:59
  • @hunterp: The code is correct (use inspector), but it's ugly because jquery (?) had added a lot of classes based on your data-listview on page load, and you added the li after page load, so it doesn't get the appropriate classes. – James S Dec 16 '12 at 22:02
  • Solution here: http://stackoverflow.com/questions/5925810/dynamically-adding-li-to-ul-in-jquery-mobile – hunterp Dec 16 '12 at 22:07
0

In an HTML document, .html() can be used to get the contents of any element. If the selector expression matches more than one element, only the first match will have its HTML content returned. Consider this code:

$('div.demo-container').html();

In order for the following 's content to be retrieved, it would have to be the first one with class="demo-container" in the document:

<div class="demo-container">
  <div class="demo-box">Demonstration Box</div>
</div>

The result would look like this:

<div class="demo-box">Demonstration Box</div>
KingKongFrog
  • 13,946
  • 21
  • 75
  • 124