Get the value of the body id and store as a variable in js

cloggy picture cloggy · Jan 23, 2013 · Viewed 10.2k times · Source

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".

Answer

John Dvorak picture John Dvorak · Jan 23, 2013

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;