最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery: Executing code for each element that matches a selector - Stack Overflow

programmeradmin4浏览0评论

$("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") 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"));
}
Share Improve this question asked Jul 18, 2010 at 10:53 PieterPieter 32.8k78 gold badges171 silver badges248 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 10
$('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

The each method sounds like what you want

$('p').each(function() {
    alert($(this).css('backgroundColor'));
}
发布评论

评论列表(0)

  1. 暂无评论