How to fix 'Typerror is undefined' message for a function in javascript?

I am trying to manipulate the background image as soon as the user hovers over a selected option. I tested my code in firebug and loaded up the page. Instantly I get:

TypeError: document.getElementsByTagName(...).style is undefined

var bg = document.getElementsByTagName("html").style.backgroundColor = "white";

and for the hover I get:

TypeError: bg.document is undefined

bg.document.getElementsByTagName("html").style.backgroundImage = "url('http://upload.wikimedia.org/wikipedia/commons/b/be/500_USD_note%3B_series_of_1934%3B_obverse.jpg')";

How do I fix this error?

HTML CODE:

<form>
    <!--show a large print of green font color and size money-->
    Select your DSLR budget range:
    <select id="budgetSel" onChange="onChange();">
        <option value="selectOneBudget" selected="selected">Select one</option>
        <option value="fiveHundredDollars" onMouseOver="changeBackgroundImage(this);">&lt; $500</option>
        <option value="thousandDollars" onMouseOver="changeBackgroundImage(this);">&lt; $1000</option>
    </select>
</form>

CSS CODE:

html{
background: url('http://upload.wikimedia.org/wikipedia/commons/8/8a/1000_USD_note%3B_series_of_1934%3B_obverse.jpg') no-repeat center center fixed;
/*-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;*/
background-size: cover;
min-width:1300px; /*keep the same width when resizing*/
}

JAVASCRIPT:

var bg = document.getElementsByTagName("html").style.backgroundColor = "white";
// function to dynamically change the background image when user hovers over an option in select menu
function changeBackgroundImage(bg)
{
   bg.document.getElementsByTagName("html").style.backgroundImage = "url('http://upload.wikimedia.org/wikipedia/commons/b/be/500_USD_note%3B_series_of_1934%3B_obverse.jpg')";
}

Answers:

Answer

as its name implies:

document.getElementsByTagName

returns a collection of tags not a single node, I said a collection because it doesn't actually return an array but it returns an array-like object.

If you only need to get the html node, you can simply do:

document.lastChild.style.backgroundColor = "white";

and also

document.documentElement.style.backgroundColor = "white";

but if you need to find it using a finder function like that, you should do this instead:

document.getElementsByTagName("html")[0].style.backgroundColor = "white";

and also this one:

document.querySelector("html").style.backgroundColor = "white";
Answer

getElementsByTagName() returns array of match elements, so you should use index 0 in your case.

Should be

document.getElementsByTagName("html")[0].style

instead of

document.getElementsByTagName("html").style

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.