Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If classlist contains more than one specific class

I need a function to trigger if the element recordplayerstick contains either the pinplace or pinsongplay class. The code I currently have returns a syntax error. What is the correct way to do this?

if (document.getElementById('recordplayerstick').classList.contains('pinplace pinsongplay')) {
    removepin();
}
like image 664
user9951515 Avatar asked Jan 14 '19 23:01

user9951515


People also ask

Can you add multiple classes with classList add?

classList propertyTo add multiple classes, you'll need to pass each class as a separate parameter to the add method. The same goes if you want to remove multiple classes. You can utilize the spread syntax if you're willing to store and manipulate your classes in an array.

How do you know if a classList contains a class?

To check if an element contains a class, you use the contains() method of the classList property of the element:*

What does the element classList toggle () method do?

toggle() The toggle() button is used for toggling classes to the element. It means adding a new class or removing the existing classes.

What does element classList do?

The Element.classList is a read-only property that returns a live DOMTokenList collection of the class attributes of the element. This can then be used to manipulate the class list. Using classList is a convenient alternative to accessing an element's list of classes as a space-delimited string via element.className .


1 Answers

Since Element.classList.contains accepts only a single class name, you need to check each separately.

You could use Array.prototype.some() to avoid writing a bunch of or conditions

const el = document.getElementById('recordplayerstick')
const classNames = ['pinplace', 'pinsongplay']
if (classNames.some(className => el.classList.contains(className))) {
  removeping()
}
like image 72
Phil Avatar answered Nov 15 '22 20:11

Phil