cloggy
cloggy

Reputation: 175

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

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

Answers (3)

Nag tech
Nag tech

Reputation: 45

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

Note that getElementsByTagName returns an array of obj

Upvotes: 1

alexg
alexg

Reputation: 3055

Yeah, try this:

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

because getElementsByTagName returns an array.

Upvotes: 2

John Dvorak
John Dvorak

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

Related Questions