最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - using classList to check for class in body - Stack Overflow

programmeradmin2浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 4

It'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;
发布评论

评论列表(0)

  1. 暂无评论