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

Share:
11,217

Related videos on Youtube

cloggy
Author by

cloggy

Updated on October 14, 2022

Comments

  • cloggy
    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
      Mathletics over 11 years
      Someone asks this question every day, and yet I can never find a suitable dupe. Please read the documentation!
  • John Dvorak
    John Dvorak over 11 years
    Note that the direct property access is much faster as well as more readable: jsperf.com/unique-by-tag-name
  • John Dvorak
    John Dvorak over 11 years
    Technically, it's a pseudo-array