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.

2  <p>This is p</p>

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);
5  $("body").append(div);

A better way to accomplish the same is presented below.

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.

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

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

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