before()
Inserts content before one or more HTML elements, which can be:
- The elements that match the selector of a script (see results).
- One element that matches the selector of a script that runs for "Each matched element" (see this and Setting the scope of a script).
- The elements returned by a query in the template (see query()).
See also: after().
before(content)
Before(content) inserts content before one or more HTML elements and creates a new result set.
content
String, HTML string or result set to insert after the elements. In case a plain text string is provided, it is automatically wrapped in a <span> element to avoid orphan text nodes to appear in the <body> element.
Examples
This script looks for an element with the ID salesrep
and inserts a paragraph before that element.
results.before("<p>Lorem Ipsum</p>");
Selector | Matched element | Matched element after script execution |
---|---|---|
#salesrep |
<p id="salesrep">Peter Parker</p> | <p>Lorem ipsum</p> <p id="salesrep">Peter Parker</p> |
This script does the same, but it uses the query() function to look up the element.
query("#salesrep").before("<p>Lorem ipsum</p>");
Matched element | Matched element after script execution |
---|---|
<p id="salesrep">Peter Parker</p> | <p>Lorem ipsum</p> <p id="salesrep">Peter Parker</p> |
The following script looks for an element with the ID salesrep, inserts a paragraph before that element and colors that element red.
query("#salesrep").before("<p>Lorem ipsum</p>").css("color","red");
Matched element | Matched element after script execution |
---|---|
<p id="salesrep">Peter Parker</p> | <p >Lorem ipsum</p> <p id="salesrep" style="color: red;">Peter Parker</p> |
Note: the way the functions before()
and css()
are used in this script is called 'chaining'. Chaining is optional; the same could be achieved by storing the
result of the query in a variable:
var salesrep = query("#salesrep");
salesrep.before("<p>Lorem ipsum</p>");
salesrep.css("color","red");
The following script searches the results for the string "ipsum" and puts "Lorem " before it. "Lorem " is automatically wrapped in a Span element.
results.find("ipsum").before("Lorem ");
Matched element | Matched element after script execution |
---|---|
<p>ipsum dolor sit amet, consectetur adipiscing elit.</p> | <p><span>Lorem </span>ipsum dolor sit amet, consectetur adipiscing elit.</p> |
The following script looks for an element with the ID salesrep and inserts the text "Lorem Ipsum" before that element. "Lorem Ipsum" is automatically wrapped in a Span element.
query("#salesrep").before("Lorem Ipsum");
Matched element | Matched element after script execution |
---|---|
<p>ipsum dolor sit amet, consectetur adipiscing elit.</p> | <span>Lorem Ipsum</span> <p id="salesrep">Peter Parker</p> |