0

It's been a while since my jQuery days and I was just struck by the realization that the following code:

$("#add").append("<div>1</div>").append("<div>2</div>")

didn't add a div with an inside div but rather two divs. I can do something like this

$("#add").append("<div>1<div>2</div></div>")

but it seems to me like hiding my ignorance, rather than producing a trustworthy solution. How can I append something with appended sub-elements?

Konrad Viltersten
  • 36,151
  • 76
  • 250
  • 438
  • Possible duplicate of [jQuery append inside appended element](http://stackoverflow.com/questions/10422501/jquery-append-inside-appended-element) – drosam Apr 03 '16 at 16:38

1 Answers1

1

You have to use .appendTo() at this context,

$("<div>1</div>").appendTo("#add").append("<div>2</div>")

Since .append() will return the element over which it(append) was invoked. So this $(#add) will be returned. Your code is very much similar to,

var elem = $("#add");
elem.append("<div>1</div>");
elem.append("<div>2</div>");
Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
  • Hmm... Perhaps I'm not clear on what I'm trying to avoid. I want the second div to be appended to the first, not the outer called add. I want the divs to be nested inside each other. – Konrad Viltersten Apr 03 '16 at 16:39
  • @KonradViltersten My code will give you an output like `
    1
    2
    ` This is what you wanted. Right?
    – Rajaprabhu Aravindasamy Apr 03 '16 at 16:41
  • That's precisely what I want. I just can't understand how it's going to be achieved using your code. Sorry if I'm being dense. I've read the docs on *appendTo* but as I follow the example, I see that the *div-2* is going to be appended to *add-div* and not nested inside *div-1*. I want to nest without actually giving the div an ID. – Konrad Viltersten Apr 03 '16 at 16:45
  • Oh, wait. I just saw it. Just to verify - I could use *$().append().appendTo* as well, right? – Konrad Viltersten Apr 03 '16 at 16:48
  • https://jsfiddle.net/8os95zkb/ I think you misread the docs. The behavior is actually depends on the returning value from the function. – Rajaprabhu Aravindasamy Apr 03 '16 at 16:48
  • How can I easily verify what element is nested in which without drawing a bunch of borders? – Konrad Viltersten Apr 03 '16 at 16:49
  • @KonradViltersten `$().append().appendTo` No, That will append elements like `
    2
    1
    `. You don't need to draw borders, you can inspect it to find that.
    – Rajaprabhu Aravindasamy Apr 03 '16 at 16:51
  • Sorry fo rnot being clear. You **are** correct and it **does** what you claim. I wonder, how I can verify for myself that it is so. Right now I do something like this: https://jsfiddle.net/8os95zkb/. – Konrad Viltersten Apr 03 '16 at 16:52
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/108094/discussion-between-rajaprabhu-aravindasamy-and-konrad-viltersten). – Rajaprabhu Aravindasamy Apr 03 '16 at 16:55