add()

The add() function adds elements to 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()).

add(content)

The add() function adds HTML content to one or more HTML elements and returns the union of this result or result set and other content.

content

A query result. This can be an HTML string or a result set.

Examples

This script adds one query result to another and sets the background color to yellow.

Copy
query("#test1").add(query("#test2")).css("background", "yellow");​

 

Note: The way the functions add() and css() are used in this script is called 'chaining'. Chaining is optional; the same could be achieved by storing the results of the queries in a variable:

Copy
var myResult = query("#test1"); 
myResult.add(query("#test2");
myResult.css("background", "yellow");

 

The following script loads snippets in an iteration and adds their elements to an empty result set (using query()). Then it replaces a placeholder in the template with the new result.

Copy
var chapters = query(); 
for ( var i = 1; i <= 4; i++) { 
chapters = chapters.add(loadhtml('snippets/Chapter' + i + '.html')); 

results.replaceWith(chapters);
Selector Matched element ​Matched element after script execution
#chapters <p id="chapters">{{chapters}}</p> <h1>Chapter 1</h1>
<p>Lorem ipsum...</p>
<h1>Chapter 2</h1>
<p>Lorem ipsum...</p>
<h1>Chapter 3</h1>
<p>Lorem ipsum...</p>
<h1>Chapter 4</h1>
<p>Lorem ipsum...</p>