I'm trying to create a test that checks the body of a webpage for a particular class using vanilla JS
currently my code looks like this
var whole = document.getElementsByTagName("body")[0];
whole.classList.contains("desiredClass");
this returns "false" on a class even though it exists in my body.
I have attempted to redefine whole as
var whole = document.body
and received the same result
Question: what is my code missing? I felt this was a pretty straightforward test, but I am certainly missing something
EDIT:
My classList function works, but was not searching for DIV classes within the body.
How do I narrow the search within the document.body to search all div classes?
I'm trying to create a test that checks the body of a webpage for a particular class using vanilla JS
currently my code looks like this
var whole = document.getElementsByTagName("body")[0];
whole.classList.contains("desiredClass");
this returns "false" on a class even though it exists in my body.
I have attempted to redefine whole as
var whole = document.body
and received the same result
Question: what is my code missing? I felt this was a pretty straightforward test, but I am certainly missing something
EDIT:
My classList function works, but was not searching for DIV classes within the body.
How do I narrow the search within the document.body to search all div classes?
Share Improve this question edited Oct 20, 2015 at 23:22 Anthony Chung asked Oct 20, 2015 at 23:02 Anthony ChungAnthony Chung 1,4772 gold badges25 silver badges46 bronze badges 2-
document.querySelector('body div.desiredClass')
? – melpomene Commented Oct 20, 2015 at 23:34 - Could you please also add the relevant HTML code? – Kyll Commented Oct 21, 2015 at 0:26
1 Answer
Reset to default 4It's not good to findElementByTagName
in this case. Using the document.body
instead is much better.
Anyway, your code seems to be ok. Maybe it's browser patibility issue?
Here you can see which versions of browsers supports classList
property of DOM element: classList doc
You can use this solution. It is much certain.
var classes = document.body.getAttribute('class').split(' ');
var contains = classes.indexOf('desiredClass') > -1;