jQuery.expr[':'].green = function(elem, index, match) { return $(elem).css("background-color") === "rgb(0, 128, 0)"; }; function updateGreenElements(){ var noGreenElems = $("*:green").length; $("#result").html(noGreenElems); } $("button").on("click", function(){ $(this).prev().toggleClass("green"); updateGreenElements(); }); updateGreenElements();
<p style="background-color: green">Hey there!</p> <ul> <li>This is a list</li> <li>Of lots of iportant stuff</li> <li class="green">Really!</li> </ul> <p>A normal paragraph</p> <p>You can click the button to toggle this one green</p> <button>Click me!</button> <p>The number of green elements on the page is: <span id="result"></span><p>
.green { background-color: green; }