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".
Just use $('#elementId').
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.
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.
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.
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;
Yeah, try this:
document.getElementsByTagName("body")[0].id
because getElementsByTagName
returns an array.
document.getElementsByTagName('body')[0].id
Note that getElementsByTagName returns an array of obj
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With