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
3 Answers
Reset to default 14getElementsByTagName
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