$("p")
references all paragraphs on the current web page. Is it possible to execute code for each element that matched the selector?
Here's a simplistic example in pseudo-code:
// Show the background color of every paragraph on the page
foreach (object = $("p")) {
alert(object.css("background-color"));
}
$('p').css('background-color', 'black')
If you need more flexibility:
$('p').each(function() {
$(this).css('background-color', 'red');
});
You can use .each()
for iterating through the matched elements, like this:
$("p").each(function() {
alert($(this).css("background-color"));
});
If you want to set or do something (e.g. not getting a value from each like above), there's no need for .each()
, just execute it and it'll run for every element on the set...this is the default jQuery behavior, for example:
$("p").show(); //shows all <p> elements
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With