---
title: "Use end more often in jQuery while building DOM elements"
description:
  "In jQuery we chain operations but we can also use end to backtrack a bit.
  This allows us to chain even more."
canonical_url: "https://www.bigbinary.com/blog/use-end-more-often-in-jquery-while-building-dom-elements"
markdown_url: "https://www.bigbinary.com/blog/use-end-more-often-in-jquery-while-building-dom-elements.md"
---

# Use end more often in jQuery while building DOM elements

In jQuery we chain operations but we can also use end to backtrack a bit. This
allows us to chain even more.

- Author: Neeraj Singh
- Published: November 11, 2009
- Categories: jQuery

I want to create following markup dynamically using jQuery.

```html
<div>
  <p>This is p</p>
</div>
```

Following jQuery code will do the work.

```javascript
$(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.

```javascript
$("<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.

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

## Links

- [Human page](https://www.bigbinary.com/blog/use-end-more-often-in-jquery-while-building-dom-elements)
