Reputation: 175
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".
Upvotes: 6
Views: 13416
Reputation: 45
document.getElementsByTagName('body')[0].id
Note that getElementsByTagName returns an array of obj
Upvotes: 1
Reputation: 3055
Yeah, try this:
document.getElementsByTagName("body")[0].id
because getElementsByTagName
returns an array.
Upvotes: 2
Reputation: 27287
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;
Upvotes: 14