Use end more often in jQuery while building DOM elements

Neeraj Singh

Neeraj Singh

November 11, 2009

I want to create following markup dynamically using jQuery.

<div>
  <p>This is p</p>
</div>

Following jQuery code will do the work.

$(document).ready(function () {
  var div = $("<div></div>");
  var p = $("<p></p>").text("this is p").appendTo(div);

  $("body").append(div);
});

A better way to accomplish the same is presented below.

$("<div></div>")
  .append("<p></p>")
  .find("p")
  .text("this is p")
  .end()
  .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.

$("<div></div>")
  .append("<p></p>")
  .find("p")
  .append("<span></span>")
  .find("span")
  .text("this is span")
  .end()
  .end()
  .appendTo("body");

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.