Use end more often in jQuery while building DOM elements

Neeraj Singh

By Neeraj Singh

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");

If you liked this blog, you might also like the other blogs we have written. Check out the full archive.

Stay up to date with our blogs. Sign up for our newsletter.

We write about Ruby on Rails, React.js, React Native, remote work,open source, engineering & design.