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 ;)
find whether all element contains same class or not
I would go another way. Rather than checking the 'success' class for all (form-group)s check if any form-group has an 'error' class or not. This way you don't need to loop over an extra array.
const formGroup = document.querySelectorAll('.form-group.error')
if(!formGroup.length) console.log('No error!!')
How can I check in JavaScript if a DOM element contains a class?
To get the whole value of the class atribute, use .className
From MDC:
className gets and sets the value of the class attribute of the specified element.
Since 2013, you get an extra helping hand.
Many years ago, when this question was first answered, .className
was the only real solution in pure JavaScript. Since 2013, all browsers support .classList
interface.
JavaScript:
if(document.getElementById('element').classList.contains("class_one")) {
//code...
}
You can also do fun things with classList
, like .toggle()
, .add()
and .remove()
.
MDN documentation.
Backwards compatible code:
if(document.getElementById('element').className.split(" ").indexOf("class_one") >= 0) {
//code...
}
Check if element has a certain class and belongs to a form that contains a certain value
To detect if an attribute on an element contains a given value you can use the Attribute contains selector. Then you can use the length
property of the resulting jQuery object to determine if anything was found.
You should also note that your logic is missing the #
selector prefix on the element
ids you use. Try this:
function isElementValid(element, color, action) { let $el = $('#' + element); let matchingClass = $el.hasClass(color); let matchingParent = $el.closest(`form[action*="${action}"]`).length != 0; return matchingClass && matchingParent;}
console.log(isElementValid('text1', 'blue', 'page2')); // falseconsole.log(isElementValid('button1', 'blue', 'page2')); // falseconsole.log(isElementValid('text3', 'blue', 'page2')); // falseconsole.log(isElementValid('text4', 'blue', 'page2')); // trueconsole.log(isElementValid('button2', 'blue', 'page2')); // trueconsole.log(isElementValid('button3', 'blue', 'page2')); // true
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><form method="post" action="/page1"> <div> <ul> <li><input type="text" id="text1" class="red" /></li> <li><input type="text" id="text2" class="red" /></li> <li><button id="button1" class="blue">Enter</button></li> </ul> </div></form><form method="post" action="/page2"> <div> <ul> <li><input type="text" id="text3" class="red" /></li> <li><input type="text" id="text4" class="blue" /></li> <li><button id="button2" class="blue">Enter</button></li> </ul> </div></form><form method="post" action="/page2andpage3"> <div> <ul> <li><input type="text" id="text5" class="red" /></li> <li><input type="text" id="text6" class="blue" /></li> <li><button id="button3" class="blue">Enter</button></li> </ul> </div></form>
How to check if an element contains a class in javascript
Try this, I have updated it to your needs.
let change = document.getElementsByClassName('change');
for(item of change){
let para =item.querySelectorAll("p");
for(let i = 0; i < para.length; i++) {
para[i].onmouseover = function () {
para[i].style.color = "red";
}
para[i].onmouseout = function () {
para[i].style.color = "black";
}
}
}
for more details check it out here
JS/jQuery - Check if element has all classes in array
Assuming that you have something like this and want a VanillaJS solution:
<div id="list-container">
<ul>
<li class="example">One</li>
<li class="example another-class">Two</li>
<li class="example">Three</li>
<li class="example">Four</li>
<li class="example">Five</li>
</ul>
</div>
You can iterate the <li>
elements and check the classes like this:
// Required classes array
let reqClasses = ['example', 'another-class'];
// Function to check if the element has the required classes
const hasClasses = (item) => {
var s = true;
reqClasses.forEach((classname) => {
if (!item.classList.contains(classname) && s) {
s = false;
}
});
return s;
}
// We get the <li> elements
let list = document
.getElementById("list-container")
.querySelectorAll('li');
// We call the function on each element and toggle visibility depending on the return
list.forEach((item) => {
if (!hasClasses(item)) {
item.style.display = 'none';
}
});
Check if element contains any of multiple classes in JavaScript
You can do if(element.matches(selector)) //returns true or false
where selector would be selector = ".class-1, .class-2, .class-3"
in your case. This works with any CSS Selector. If you want every class to be present, you would need selector = ".class-1.class-2.class-3
for example. You can learn more about CSS-Selectors here: https://www.w3schools.com/cssref/css_selectors.asp
Related Topics
Download File Using an Ajax Request
How to Prevent Buttons from Submitting Forms
Why Calling Setstate Method Doesn't Mutate the State Immediately
Changing Website Favicon Dynamically
Get File Size, Image Width and Height Before Upload
Html Form Readonly Select Tag/Input
How to Turn Off Antialiasing on an HTML ≪Canvas≫ Element
Detect Which Word Has Been Clicked on Within a Text
How to Disable HTML Button Using JavaScript
Open Links Made by Createobjecturl in Ie11
How to Save an Html5 Canvas as an Image on a Server
Jquery Mobile: Document Ready Vs. Page Events
How to Change the Href Attribute For a Hyperlink Using Jquery
How to Call Multiple JavaScript Functions in Onclick Event
How Does Content Security Policy (Csp) Work
Html Script Tag: Type or Language (Or Omit Both)
How to Simulate a Hover With a Touch in Touch Enabled Browsers