jQuery how to check if the class name contains a certain value
I would like to read out the classnames attached to a certain element and take action based on that the classname contains a certain value 开发者_高级运维("active"). The classname could be something like: class="bla-bla-bla first active". What is the best way to do that?
Class names are separated by spaces, so you just need $(something).hasClass('active')
Additionally, you could use the .is()
method, like this: $(somthing).is('.active')
, which returns true
or false
.
Finally, you might be better off using it as the selector, like so: $('li.active').doSomething()
You'd simply use the .is function. For example if you had a div <div id="divid" class="bla-bla-bla first active" /> you could use:
if ($('#divid').is('.active')) { alert('Its active!'); }
This method will work with any jQuery selector syntax meaning you can do some pretty in-depth checks with this far beyond just css class. See the jQuery documentation for more info.
If you are looking for a specific class of an element within one to many elements, you can use this:
if(element.classList.contains("myStyle")){
// works for one or more class names
// if "myStyle" is one of the classnames present
// then run your code here
alert("This one has the class myStyle!";
}
But if you are looking for specific text, like a substring within a certain classname then you might consider something like below. My case is that the class of the div's I need contain a partial string within a larger classname, like "answer--anYKw3yE". If it has the word "answer" in it then I know it has data that I need. But the remaining characters of the class are javascript generated and change everytime the page refreshes. So I make a collection of all elements by tagname for instance and then loop through that collection looking for a substring within the classnames. When it finds the substring within any classname of any element, then I know that I need that elements' innertext.
var tablas = document.getElementsByTagName("table")[0].getElementsByTagName("tr")
if(tablas.className.includes("answer")){
// this tr does have a classname with the substring
// 'answer' in at least one of it's classnames.
alert("Wowsie woo woo!");
}
精彩评论