Back to Blog

Use end more often in jQuery while building DOM elements

on November 11, 2009

I want to create following markup dynamically using jQuery.

1<div>
2  <p>This is p</p>
3</div>

Following jQuery code will do the work.

1$(document).ready(function () {
2  var div = $("<div></div>");
3  var p = $("<p></p>").text("this is p").appendTo(div);
4
5  $("body").append(div);
6});

A better way to accomplish the same is presented below.

1$("<div></div>")
2  .append("<p></p>")
3  .find("p")
4  .text("this is p")
5  .end()
6  .appendTo("body");

Using .end() you can go back one level. And you can use .end() any number of times to get out of a deeply nested tag.

1$("<div></div>")
2  .append("<p></p>")
3  .find("p")
4  .append("<span></span>")
5  .find("span")
6  .text("this is span")
7  .end()
8  .end()
9  .appendTo("body");

You might also like

If you liked this blog post, check out similar ones from BigBinary