JQuery: Code execution for every element that matches a selector

$("p") refers to all paragraphs on the current web page. Is it possible to execute code for each element that matches the selector?

Here's a simplified example in pseudo code:

 // Show the background color of every paragraph on the page foreach (object = $("p")) { alert(object.css("background-color")); } 
+7
javascript jquery html
source share
3 answers
 $('p').css('background-color', 'black') 

If you need more flexibility:

 $('p').each(function() { $(this).css('background-color', 'red'); }); 
+9
source share

You can use .each() to iterate through matched elements, for example:

 $("p").each(function() { alert($(this).css("background-color")); }); 

If you want to set or do something (for example, not getting a value from each, as mentioned above), there is no need for .each() , just execute it and it will be run for every element in the set ... this is jQuery behavior by default, for example:

 $("p").show(); //shows all <p> elements 
+5
source share

each method sounds the way you want

 $('p').each(function() { alert($(this).css('backgroundColor')); } 
0
source share

All Articles