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

javascript - Get the value of the body id and store as a variable in js - Stack Overflow

programmeradmin9浏览0评论

I have a need to change something within a page depending on the body tag id.

My code doesn't seem to work, can you help?

function changeHeaderTitle(){
    var bodyId = document.getElementsByTagName("body").id;
    alert(bodyId);
}

This just echoes "undefined".

I have a need to change something within a page depending on the body tag id.

My code doesn't seem to work, can you help?

function changeHeaderTitle(){
    var bodyId = document.getElementsByTagName("body").id;
    alert(bodyId);
}

This just echoes "undefined".

Share Improve this question edited Jan 23, 2013 at 17:57 John Dvorak 27.3k13 gold badges72 silver badges85 bronze badges asked Jan 23, 2013 at 17:56 cloggycloggy 1753 gold badges3 silver badges10 bronze badges 1
  • 3 Someone asks this question every day, and yet I can never find a suitable dupe. Please read the documentation! – Evan Davis Commented Jan 23, 2013 at 18:03
Add a ment  | 

3 Answers 3

Reset to default 14

getElementsByTagName returns collection of nodes, even if the collection is bound to contain only one element. Try

var bodyId = document.getElementsByTagName("body")[0].id;
// select the first (and only) body:              ^^^

or better yet

var bodyId = document.body.id;

Yeah, try this:

 document.getElementsByTagName("body")[0].id

because getElementsByTagName returns an array.

document.getElementsByTagName('body')[0].id

Note that getElementsByTagName returns an array of obj

发布评论

评论列表(0)

  1. 暂无评论