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();
}
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.
To check if an element contains a class, you use the contains() method of the classList property of the element:*
toggle() The toggle() button is used for toggling classes to the element. It means adding a new class or removing the existing classes.
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 .
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()
}
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