Sony ThePony Sony ThePony - 1 month ago 4
jQuery Question

If statement, act on the element being checked

noob question here.

Let's say I want to check through my document and see if a p element has a class.

if ( $('p').hasClass('theClass') ) {}

It will return true or false based on checking all p elements (or will it stop after it finds the first true??)

If it checks all elements, can you get it to execute a method on all true elements?

if ( $('p').hasClass('theClass') ) {


.hasClass( className ): Determine whether any of the matched elements are assigned the given class.

So, $('p').hasClass('theClass') returns true or false and not the list of all element having the class.

For this you need to select elements by tagname and class (just to replace your example): $('p.theClass') and this will returns the list you need on which you can apply a loop:

$(function () {
  var x = $('p').hasClass('theClass');
  console.log("$('p').hasClass('theClass') returns: " + x);
  console.log("$('p.theClass') returns a list of N. " + $('p.theClass').length + " elements");
  // In case you need to loop:
  $('p.theClass').each(function(index, element) {
    // do other stuff....
  // If you need only to set the color you may reduce all to one line
<script src=""></script>

<p class="theClass">2</p>
<p class="theClass">4</p>
<p class="theClass">6</p>
<p class="theClass">8</p>