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 } });
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.
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.
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.
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.
function doSomething(){ if ($(this).hasClass('clickedTag')){ // code here } else { // and here } } $('.tag1').click(doSomething); $('.tag2').click(doSomething); // or, simplifying further $(".tag1, .tag2").click(doSomething);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With