Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 847
cloggy Avatar asked Jan 23 '13 17:01

cloggy


People also ask

How do you store the element value with an ID into a Javascript variable?

Just use $('#elementId').

How do you store the value of a function in a variable in Javascript?

Functions stored in variables do not need function names. They are always invoked (called) using the variable name. The function above ends with a semicolon because it is a part of an executable statement.

How do you store variables in HTML?

Use the <var> tag in HTML to add a variable. The HTML <var> tag is used to format text in a document. It can include a variable in a mathematical expression.

What does body mean in Javascript?

body in javascript is a direct reference to the DOM element representing the <body> portion of the page. The $() part depends on how it is used. $ could be a variable name, and () after a variable or property name attempts to call a function stored in that variable or property.


3 Answers

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;
like image 139
John Dvorak Avatar answered Sep 22 '22 04:09

John Dvorak


Yeah, try this:

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

because getElementsByTagName returns an array.

like image 29
alexg Avatar answered Sep 24 '22 04:09

alexg


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

Note that getElementsByTagName returns an array of obj

like image 35
Nag tech Avatar answered Sep 22 '22 04:09

Nag tech