Bug Tracker

Opened 15 years ago

Closed 15 years ago

#2909 closed enhancement (worksforme)

hasClass() method

Reported by: chrishandorf Owned by:
Priority: minor Milestone: 1.2.4
Component: core Version: 1.2.3
Keywords: Cc:
Blocked by: Blocking:

Description

On many occasions inside a function I find the need to test for the existence of a class on an unknown jquery element. A class string may consist of many individual classes such as "folder selected draggable".

I can do this but it seems ugly:

   function myFunction(elem) {
      if (elem.attr("class").indexOf("selected") != -1)

It would be better if I could do this:

   function myFunction(elem) {
      if (elem.hasClass("selected"))

It seems like a hasClass() method in core jQuery would be useful to everyone. Is there a better way?

   /* Checks for the existence of a single class */
   $.fn.hasClass = function(className) {
       var classes = this.attr("class").split(" ");
       for (var x in classes) {
         if (classes[x] == className) return true;
       }
       return false;
   }

Change History (2)

comment:1 Changed 15 years ago by ThrushAAX

comment:2 Changed 15 years ago by scott.gonzal

Resolution: worksforme
Status: newclosed
Note: See TracTickets for help on using tickets.