.hasClass() JQ Home  <<  A & P  <<  .hasClass()

Finding classes in CSS.

Description

The .hasClass() method is used to determine whether the specified class is assigned to any elements within the matched set.

  • Returns true if any of the classes for the element match the specified class.

Syntax

Signature Description
.hasClass(className)A class to look for.

Parameters

Parameter Description Type
classNameA class name.String

Return

A Boolean object.

.hasClass( className ) Example A & P  <<  Top

Determine whether the specified class is assigned to any elements within the matched set.

In the example below when we press the button we iterate over all 'td' elements within the table and turn the background colour to orange if they contain a class 'turnAqua' .

Table For Testing The .hasClass( className ) Signature
Table Row 1, Table Data 1  (class of turnAqua) Table Row 1, Table Data 2
Table Row 2, Table Data 1  (class of turnAqua) Table Row 2, Table Data 2  (class of turnAqua)
Table Row 3, Table Data 1  (class of turnAqua) Table Row 3, Table Data 2
Table Row 4, Table Data 1 Table Row 4, Table Data 2  (class of turnAqua)



$(function(){
  $('#btn8').on('click', function() {
    $('.testtable td').each(function (index, tableElement) { 
       if ($(this).hasClass('turnAqua')) {
           $(this).css('backgroundColor', 'orange');
       };
    });
  });
});


Press the button below to action the above code:

Related Tutorials

jQuery Basic Tutorials - Lesson 8 - Working With CSS Classes