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

javascript - get element by id and then class attribute - Stack Overflow

programmeradmin1浏览0评论

I am trying to get an elements class name. First I find the element by its id and then I tried to get the class attribute doing the following. My results return undefined. How can I get the text from the class attribute? Which would be "not-checked-in".

html

<div id="last-check-in" class="not-checked-in"></div>

javascript

var checkedin;
checkedin = document.getElementById("last-check-in");
console.log(checkedin.class);

I am trying to get an elements class name. First I find the element by its id and then I tried to get the class attribute doing the following. My results return undefined. How can I get the text from the class attribute? Which would be "not-checked-in".

html

<div id="last-check-in" class="not-checked-in"></div>

javascript

var checkedin;
checkedin = document.getElementById("last-check-in");
console.log(checkedin.class);
Share Improve this question edited Sep 13, 2012 at 4:32 Felix Kling 818k181 gold badges1.1k silver badges1.2k bronze badges asked Sep 13, 2012 at 4:17 DanielDaniel 4,36212 gold badges52 silver badges69 bronze badges 1
  • possible duplicate of DOM attribute access: why is "elt.class" not working? – Felix Kling Commented Sep 13, 2012 at 4:34
Add a ment  | 

2 Answers 2

Reset to default 3

Instead of simply class, use className:

var checkedin = document.getElementById("last-check-in");
console.log(checkedin.className);

You may use: getAttribute("class")

var checkedin;
checkedin = document.getElementById("last-check-in");
console.log(checkedin.getAttribute("class"));

DEMO

发布评论

评论列表(0)

  1. 暂无评论