Bug Tracker

Ticket #2909 (closed enhancement: worksforme)

Opened 6 years ago

Last modified 6 years ago

hasClass() method

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

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

comment:1 Changed 6 years ago by ThrushAAX

comment:2 Changed 6 years ago by scott.gonzal

  • Status changed from new to closed
  • Resolution set to worksforme
Note: See TracTickets for help on using tickets.