乐闻世界logo
搜索文章和话题

How to check if an element contains a class in javascript

2个答案

1
2

{"title":"How to Check if an Element Contains a Specific Class in JavaScript?","content":"In JavaScript, you can use the Element.classList property to check if an element contains a specific class. classList is a read-only property that returns a DOMTokenList collection of the element's class attribute. The contains() method checks if the collection includes the specified class name and returns true if present, otherwise false.

Here is an example of using the classList.contains() method to check for a specific class:

javascript
// Assume there is an element <div id=\"myDiv\" class=\"foo bar baz\"></div> var elem = document.getElementById('myDiv'); // Check if the element contains class 'foo' if (elem.classList.contains('foo')) { console.log('Element contains class \"foo\"'); } else { console.log('Element does not contain class \"foo\"'); } // Check if the element contains class 'no-such-class' if (elem.classList.contains('no-such-class')) { console.log('Element contains class \"no-such-class\"'); } else { console.log('Element does not contain class \"no-such-class\"'); }

In the above code, we first retrieve the DOM element with ID myDiv using document.getElementById, then use the classList.contains method to verify the presence of a specific class. Based on the method's return value, you can implement appropriate logic or provide user feedback."}

2024年6月29日 12:07 回复

A simple and effective solution is to use the .contains method. test.classList.contains(testClass);

2024年6月29日 12:07 回复

你的答案