Adding New DOM Elements
Learn about how different jQuery methods such as append(), prepend(), after(), and before() add new elements to the DOM tree.
We'll cover the following...
With jQuery we can insert and add new HTML elements to a DOM tree using methods such as append(), prepend(), after() and before().
Let’s look at all these methods in detail, along with relevant examples.
append() and prepend() methods
These methods add new HTML child elements within the specified element.
The
append()method attaches a new element as the last child of the specified element.
The
prepend()method attaches a new element as the first child of the specified element.
The new HTML element(s) are passed as argument(s) to these methods.
- A single element is passed directly as an argument:
('selector').method(element)
- Multiple elements are passed either as a single list or as multiple individual arguments:
// using list of elements
var listItems = [elemA,elemB,elemC]
('selector').method(listItems)
// using multiple individual arguments
('selector').method(elemA,elemB,elemC)
Consider the web page in the illustration above. We have a p element nested within a div element. We also have two button elements, with text “append” and “prepend,” inside the p element. We assign click event handlers to both the “append” and “prepend” buttons. In the “append” button event handler function, we attach a new span child element at the end of the given p element using the append() method (line 3). Similarly, in the “prepend” button event handler function, we attach a new span child element at the start of the given p element using the prepend() method (line 7).
Run the code below. In the web page output, click on the “append” button. Observe how a new
spanchild element appears at the end of the givenpelement. Now, click on the “prepend” button and see how a newspanchild element appears at the start of the givenpelement.
after() and before() methods
These methods insert new HTML sibling elements outside the specified element.
The
after()method attaches a next sibling element after the specified element.
The
before()method attaches a previous sibling element before the specified element.
The syntax for arguments, along with single and multiple elements, is the same as for append() and prepend().
In the example discussed above, we replace the append() and prepend() methods with after() and before() respectively. We also change the “append” and “prepend” button text with “after” and “before.”
Run the code below. In the web page output, click on the “after” button. Observe the new
spansibling element appearing after the givenpelement. Now, click on the “before” button. Observe how a newspansibling element appears before the givenpelement.