Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Executing code for each element that matches a selector

$("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"));
}
like image 352
Pieter Avatar asked Jul 18 '10 10:07

Pieter


2 Answers

$('p').css('background-color', 'black')

If you need more flexibility:

$('p').each(function() {
    $(this).css('background-color', 'red');
});
like image 84
meder omuraliev Avatar answered Nov 03 '22 09:11

meder omuraliev


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
like image 38
Nick Craver Avatar answered Nov 03 '22 07:11

Nick Craver