HTML DOM Element before()
Example
Insert text before a div:
const div = document.getElementById("myDiv");
div.before("World!");
Try it Yourself »
div.before("World!");
Example
Insert an element before a div:
const div = document.getElementById("myDiv");
const h3 = document.createElement("h3");
div.before(h3);
h3.append("Hello! I am an h3");
Try it Yourself »
const h3 = document.createElement("h3");
div.before(h3);
h3.append("Hello! I am an h3");
More "Try it Yourself" examples below.
Description
The before()
method is used to insert one or
more nodes (elements)
or strings immediately before an element.
Tip: Strings will be inserted as Text nodes.
Syntax
element.before(node1, node2, ...)
Parameters
Parameter
Description
node
Required. One or more nodes or strings to insert before the element
Return Value
None
Browser Support
Method | |||||
---|---|---|---|---|---|
before() | 54 | 17 | 49 | 10 | 39 |
See Also:
Related Document Methods:
More Examples
Example
Insert two elements and a text before a div:
const div = document.getElementById("myDiv");
const h3 = document.createElement("h3");
const h4 = document.createElement("h4");
div.before(h3, h4, "Some text!");
h3.append("Hello! I am an h3");
h4.append("Hello! I am an h4");
Try it Yourself »
const h3 = document.createElement("h3");
const h4 = document.createElement("h4");
div.before(h3, h4, "Some text!");
h3.append("Hello! I am an h3");
h4.append("Hello! I am an h4");