each()
A generic iterator function, to iterate over the elements in a result set.
each()
function to loop over a result set, you could set the scope of a Standard script or Post Pagination script to "Each matched element" and access each matched element directly via the this
object. See Setting the scope of a script and this.each(callback)
Iterates over the elements in a set, such as the enumerable properties of an object, in arbitrary order. For each distinct property, statements can be executed.
callback
A function. The callback function is passed the iteration index and the current element.
In the scope of the callback function, this
refers to the current element.
Examples
The following scripts demonstrate a simple iteration over the elements in
the results
(the set of HTML elements that match the selector of the script).
The first script sets the background color of each of the elements to red. (This is just to demonstrate how this function works. It is easier to change the style of a set of HTML elements using the css()
function; see css().)
results.each(function(index){
results[index].css('background-color','red');
});
This script adds a random integer to each element in the result set.
results.each(function(index){
var test = Math.floor((Math.random() * 10) + 1);
this.html(test);
});
Selector | Matched element | Matched element after script execution |
---|---|---|
p | <p></p> <p></p> <p></p> |
<p>3</p> <p>1</p> <p>7</p> |
The next script gets the row index (of the current element in the set) and puts it in a paragraph.
results.each(function(index){
this.text(index);
}
Selector | Matched element | Matched element after script execution |
---|---|---|
p | <p></p> <p></p> <p></p> |
<p>0</p> <p>1</p> <p>2</p> |
Using each()
in a translation script
The following script first loads a snippet containing translation strings, depending on the value of a field. Then it inserts translations by iterating over elements in the results
(the set of HTML elements that match the selector of the script) and
setting the HTML of each element with a value from the array of translation strings.
var strings = loadjson('snippets/' + record.fields.locale + '.html');
results.each(function(index){
if( strings[this.attr('data-translate')])
this.html(strings[this.attr('data-translate')]);
});
Note: for documentation on the data-*
attribute, see https://www.w3schools.com/tags/att_global_data.asp.
Selector | Matched element | Matched element after script execution |
---|---|---|
p |
<p data-translate="first"></p> |
<p>primero</p> <p>último</p> <p>dirección de correo electrónico</p> |