.hasClass()S2C Home « Attributes & Properties « .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 jQuery object.

.hasClass( className ) ExampleTop

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: