Now we know how to select and then apply jQuery functions like this;
$('img').fadeOut(); // applies .fadeOut() too all <img> elements
fadeOut() is a jQuery built-in function. What if you want to loop
through a selection of elements and perform a series of operations
you write yourself (instead of fadeOut)? You use
each().
.each() -- iterate over a jQuery object and execute a function for each matched element [
jq_02_each.html]
<!DOCTYPE html>
<html>
<head>
<title>jQuery</title>
<script src="http://code.jquery.com/jquery-3.2.1.js"></script>
</head>
<body>
<p> paragraph 1 </p>
<p> paragraph 2 </p>
<p> paragraph 3 </p>
<script>
$('p').each(function(){
alert( $(this).text() ); // note that this is pure javascript
});
</script>
</body>
</html>
First, you apply the .each() function to your jQuery selection.
$('p').each();
The each() function takes a function as an argument. That function gets executed
for each element that is selected by your jQuery selection.
To do something to what you've selected,
you need to pass what is called an
anonymous function. The anonymous function describes what is to be done the selection.
It is anonymouse because it is a function that does not have a name.
To pass an anonymous function as an argument to the each() function, first you
need to know what an anonymous function looks like:
function(){
// code goes here
}
You literally squeeze in the anonymous function in between the parenthesis
as an argument to each()
$('p').each(
function(){
// code goes here
}
);
Often times, it is organized like this with the all the parenthesis and brackets in one line
$('p').each(function(){
// code goes here
});
this and $(this) -- when using the
each() function, you'll want to address each of the elements. To
access the current element, you use
this or
$(this) .
this returns a
traditional DOM element
and
$(this) returns a
jQuery
equivalement. [
jq_02_each_this.html]
<!DOCTYPE html>
<html>
<head>
<title>jQuery</title>
<style>
.highlight {
background: yellow;
}
</style>
<script src="http://code.jquery.com/jquery-3.2.1.js"></script>
</head>
<body>
<p> paragraph 1 </p>
<p> paragraph 2 </p>
<p> paragraph 3 </p>
<script>
$('p').each(function(){
$(this).addClass('highlight'); // jquery
this.innerHTML = "hello"; // JavaScript
});
</script>
</body>
</html>
[
jq_02_bibliography.html]
<script>
$(document).ready(function(){
$('a').each(function(){
var link = $(this).clone();
$('#bib').append("- ").append(link).append("<br>");
});
})
</script>
$(document).ready();
<script>
$(document).ready(
function(){};
);
</script>