Get the value of the body id and store as a variable in js
11,217
Solution 1
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;
Solution 2
Yeah, try this:
document.getElementsByTagName("body")[0].id
because getElementsByTagName
returns an array.
Solution 3
document.getElementsByTagName('body')[0].id
Note that getElementsByTagName returns an array of obj
Related videos on Youtube
Author by
cloggy
Updated on October 14, 2022Comments
-
cloggy over 1 year
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".
-
Mathletics over 11 yearsSomeone asks this question every day, and yet I can never find a suitable dupe. Please read the documentation!
-
-
John Dvorak over 11 yearsNote that the direct property access is much faster as well as more readable: jsperf.com/unique-by-tag-name
-
John Dvorak over 11 yearsTechnically, it's a pseudo-array