views:

39

answers:

3

$("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"));
}
+3  A: 

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
Nick Craver
+5  A: 
$('p').css('background-color', 'black')

If you need more flexibility:

$('p').each(function() {
    $(this).css('background-color', 'red');
});
meder
Thanks, this works!
Pieter
A: 

The each method sounds like what you want

$('p').each(function() {
    alert($(this).css('backgroundColor'));
}
Dan F
As an aside here, `backgroundColor` is there to use as a property, like `{ backgroundColor: 'red', color: 'green' }`, but when using a string there's no need to use anything but the standard syntax (easier to find when you're debugging too). `backgroundColor` gets transformed back to `background-color` under the covers when it runs, no need to convert it here just to create extra work :)
Nick Craver
Ah, nice, thanks for that Nick. I use it this way out of force of habit. Must be time to break that habit :-)
Dan F