What is the hasClass function with plain JavaScript?
You can check whether element.className
matches /\bthatClass\b/
.\b
matches a word break.
Or, you can use jQuery's own implementation:
var className = " " + selector + " ";
if ( (" " + element.className + " ").replace(/[\n\t]/g, " ").indexOf(" thatClass ") > -1 )
To answer your more general question, you can look at jQuery's source code on github or at the source for hasClass
specifically in this source viewer.
If element has class
As noted in the jquery docs: https://api.jquery.com/class-selector/
The selector for objects with a class is not
$("wgcurrent")
It's like this:
$(".wgcurrent")
The dot makes it so it selects any object with the wgcurrent class.
I believe that's the reason behind your issue, since the hasClass should work in this scenario.
However beware that this will select ALL the objects with the wgcurrent class.
Check if an element contains a class in JavaScript?
Use element.classList
.contains
method:
element.classList.contains(class);
This works on all current browsers and there are polyfills to support older browsers too.
Alternatively, if you work with older browsers and don't want to use polyfills to fix them, using indexOf
is correct, but you have to tweak it a little:
function hasClass(element, className) {
return (' ' + element.className + ' ').indexOf(' ' + className+ ' ') > -1;
}
Otherwise you will also get true
if the class you are looking for is part of another class name.
DEMO
jQuery uses a similar (if not the same) method.
Applied to the example:
As this does not work together with the switch statement, you could achieve the same effect with this code:
var test = document.getElementById("test"),
classes = ['class1', 'class2', 'class3', 'class4'];
test.innerHTML = "";
for(var i = 0, j = classes.length; i < j; i++) {
if(hasClass(test, classes[i])) {
test.innerHTML = "I have " + classes[i];
break;
}
}
It's also less redundant ;)
How do you find out if an HTML element has a certain class with plain Javascript?
if(document.getElementById("hello").className.split(" ").indexOf("option") > -1);
That'll do it.
EDIT: demo
or as a prototyped function:
HTMLElement.prototype.hasClass = function(c){
return this.className.split(" ").indexOf(c) > -1
}
and
document.getElementById("hello").hasClass("option")
Update 2015:
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)
How do I use hasClass to detect if a class is NOT the class I want?
Yes, you can.
if (!$('element').hasClass('do-not-want')) {
// This element does not have the .do-not-want class
}
Determine if an element has a CSS class with jQuery
Use the hasClass
method:
jQueryCollection.hasClass(className);
or
$(selector).hasClass(className);
The argument is (obviously) a string representing the class you are checking, and it returns a boolean (so it doesn't support chaining like most jQuery methods).
Note: If you pass a className
argument that contains whitespace, it will be matched literally against the collection's elements' className
string. So if, for instance, you have an element,
<span class="foo bar" />
then this will return true
:
$('span').hasClass('foo bar')
and these will return false
:
$('span').hasClass('bar foo')
$('span').hasClass('foo bar')
If element with ID has as class
getElementById
returns a DOMNode and there is no hasClass
method in DOMNode
.
You may want to use a library, like jQuery:
jQuery('#game_' + variable).hasClass('current_nav')
Check if class exists somewhere in parent
You'll have to do it recursively :
// returns true if the element or one of its parents has the class classname
function hasSomeParentTheClass(element, classname) {
if (element.className.split(' ').indexOf(classname)>=0) return true;
return element.parentNode && hasSomeParentTheClass(element.parentNode, classname);
}
Demonstration (open the console to see true
)
hasClass() function not detecting -- preceding function won't run
when using addClass()
, removeClass()
or hasClass()
you do not use a period , just use the class name ex:
.hasClass('cboxPhoto')
see jQuery docs here
className
Type: String
The class name to search for.
$( "#mydiv" ).hasClass( "foo" )
no errors are going to show up, it is still valid code , but it wil never find the class name you are looking for
UPDATE
see your code :
var imgs = $('img');
if ($(img).hasClass('cboxPhoto')) {
you have not defined img
at this line
Related Topics
How to Check If a Custom Protocol Supported
How to Call an Async Function Inside a Useeffect() in React
JavaScript Keycode VS Charcode
How to Make a Shared State Between Two React Components
Angular 4 Interceptor Retry Requests After Token Refresh
Javascript:Send JSON Object with Ajax
Access JavaScript Property Case-Insensitively
How to Set Bootstrap Navbar Active Class with Angular Js
Calculating Page Load Time in JavaScript
Shiny Slider Input Step by Month
How to Create an Object from an Array of Key-Value Pairs
Detect Blocked Popup in Chrome
Download a Div in a HTML Page as PDF Using JavaScript
Angular Cli Webpack, How to Add or Bundle External Js Files