Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning more than one class for one event

I have an click event that I want to assign to more than class. The reason for this is that I'm using this event on different places in my application, and the buttons you click have different styling in the different places.

What I want is something like $('.tag' '.tag2'), which of course don't work.

    $('.tag').click(function (){         if ($(this).hasClass('clickedTag')){             // code here         }          else {              // and here         }     }); 
like image 477
holyredbeard Avatar asked May 09 '12 07:05

holyredbeard


People also ask

How do you select an element with multiple classes?

Use the getElementsByClassName method to get elements by multiple class names, e.g. document. getElementsByClassName('box green') . The method returns an array-like object containing all the elements that have all of the given class names.

Can we add more than one CSS classes to the selected elements using the addClass () method?

The addClass() method adds one or more class names to the selected elements. This method does not remove existing class attributes, it only adds one or more class names to the class attribute. Tip: To add more than one class, separate the class names with spaces.

Can you add multiple classes to an element JQuery?

Given an HTML element and the task is to add and remove multiple classes from it using JQuery. Approach: First select the element to which multiple classes will be added. Then use addClass() method to add multiple classes to the element and removeClass() method to remove multiple classes.

How can use two classes in JQuery?

The . class selector can also be used to select multiple classes. Note: Seperate each class with a comma. Note: Do not start a class attribute with a number.


1 Answers

Approach #1

function doSomething(){     if ($(this).hasClass('clickedTag')){         // code here     }     else {          // and here     } }  $('.tag1').click(doSomething); $('.tag2').click(doSomething);  // or, simplifying further $(".tag1, .tag2").click(doSomething); 

Approach #2

This will also work:

​$(".tag1, .tag2").click(function(){    alert("clicked");     });​ 

Fiddle

I prefer a separate function (approach #1) if there is a chance that logic will be reused.

See also How can I select an element with multiple classes? for handling multiple classes on the same item.

like image 146
Tim M. Avatar answered Sep 28 '22 18:09

Tim M.