JavaScript’s Element.after()
method inserts a set of Node
or string objects after the Element
.
Syntax
Element.after(parameter1)
Element.after(parameter1, parameter2, /* … , */ parameterN)
Parameters
One or more Node
or string objects.
Return value
The after()
method does not have a return value, which means that the method implicitly returns undefined
.
Exceptions
HierarchyRequestError
DOMException
Thrown when the node cannot be inserted at the specified point in the hierarchy.
Examples
Here are some examples of using the JavaScript after()
method.
Inserting an element
Suppose we have the following paragraph after which we would like to add another paragraph:
<p id="paragraph">JavaScript is a popular programming language.</p>
How could we do that?
How about selecting the first paragraph with the getElementById()
method, creating a new paragraph, and using the after()
method to insert the new paragraph after the first paragraph:
let first = document.getElementById('paragraph');
let p = document.createElement('p');
p.textContent = '…and learning JavaScript is surprisingly easy.';
first.after(p);
Now our HTML looks – surprisingly – like this:
<p id="paragraph">JavaScript is a popular programming language.</p>
<p>…and learning JavaScript is surprisingly easy.</p>
Inserting text
Instead of a p
element, we could have inserted a string object after the first paragraph:
let first = document.getElementById('paragraph');
first.after('…and learning JavaScript is surprisingly easy.');
Browser compatibility
Chrome
|
Edge
|
Firefox
|
Internet Explorer
|
Opera
|
Safari
|
Chrome (Android)
|
Firefox (Android)
|
Opera (Android)
|
Safari (iOS)
|
Samsung Internet
|
WebView (Android)
|
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
after() |
54 | 17 | 49 | 39 | 10 | 54 | 49 | 41 | 10 | 6.0 | 54 |