Aquaplanet
Aquaplanet

Reputation: 583

About jquery append behavior

I have the following code:

$.getJSON('/api/video/',
      function (resp) {
          $("body").append("<ul/>");

          $.each(resp, function (key, value) {
              $("ul").append("<li/>").append(
                  $("<a/>", {
                      href: value.url,
                      html: value.title
                  }));
          });
      });

It produces:

...
<ul>
    <li></li>
    <a href="http://vimeo.com/1234567">How to Connect a Mobile Broadband Antenna to Data Card</a>
    <li></li>
    <a href="http://www.youtube.com/watch?v=q4Oknc8onG8">40000mW Laser vs. Line of Balloons!!</a>
</ul>
...

As you can see the <a/> are not inside <li/> and my question is why (is there a good reason for the behavior or does it just work that way)? In my world $("ul").append("<li/>").append($("<a/>", ...)) adds the <a/> inside a <li/>. I see it as $("ul").append("<li/>") creates an <li/> inside the unorderd list and that the next append operates on the <li/> item and thus should add the link inside of it. However that is not the case and I wonder if there is a reason for that?

I am very grateful that you have taken time for my question!

Upvotes: 1

Views: 68

Answers (2)

Anthony Grist
Anthony Grist

Reputation: 38345

The .append() function doesn't update the element(s) referenced by the jQuery object, so when you call the second .append() it's still being called against the <ul> element.

You could restructure it like so:

$('<li/>').append('<a/>', {
    href: value.url,
    title: value.title
}).appendTo('ul');

Upvotes: 4

Elliot Bonneville
Elliot Bonneville

Reputation: 53291

$.append() returns the item that was appended to, not the item being appended.

Upvotes: 1

Related Questions