jQuery before: Main Tips
- jQuery
.before()
inserts content before the selected elements. To add it after elements, use .after(). - While it achieves the same goal as .insertBefore, jQuery
.before()
uses different syntax.
Usage and Syntax of before
The .before
jQuery method inserts additional content before the defined element (one or multiple). In the example below, extra text is displayed before the heading:
$("button").click(() => {
$("h1").before("<p>Get ready!</p>");
});
The syntax for jQuery .before()
is as follows:
$(selector).before(content);
- The
content
can specify either exact content or a function that returns it. - In jQuery
before
,selector
specifies the elements the new elements will be added to.
Note: the content to insert might have a value of a jQuery object, HTML string, DOM element, a text node, or an array of either elements or nodes.