Skip to main content

Bug Tracker

Side navigation

#2909 closed enhancement (worksforme)

Opened May 21, 2008 12:19AM UTC

Closed May 21, 2008 02:14AM UTC

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;
   }
Attachments (0)
Change History (2)

Changed May 21, 2008 01:18AM UTC by ThrushAAX comment:1

Changed May 21, 2008 02:14AM UTC by scott.gonzal comment:2

resolution: → worksforme
status: newclosed