Say I have this html element
<div id="hello" class="hello option john">Hello</div>
<div id="hello" class="hello john">Hello</div>
. Now I select the element with javascript by it's Id. How would I do an equivalent of if($('hello').hasClass('option')){//do stuff}
(jQuery) except in plain Javascript?
Use the classList. contains() method to check if an element does not have a specific class, e.g. if (! el. classList.
Open the page in a browser, like Chrome or Firefox, right click and inspect the element, You should see the source, there you can see the class.
The JavaScript getElementsByClassName is used to get all the elements that belong to a particular class. When the JavaScript get element by class name method is called on the document object, it searches the complete document, including the root nodes, and returns an array containing all the elements.
if(document.getElementById("hello").className.split(" ").indexOf("option") > -1);
That'll do it.
or as a prototyped function:
HTMLElement.prototype.hasClass = function(c){
return this.className.split(" ").indexOf(c) > -1
}
and
document.getElementById("hello").hasClass("option")
In modern browsers including IE 10 you can write:
document.getElementById("hello").classList.contains("option")
See the reference: https://developer.mozilla.org/en-US/docs/Web/API/Element/classList
It's supported in all major browsers (ref: http://caniuse.com/#search=classlist)
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