I am starting out using JavaScript and I cannot understand why I cannot assign a HTML attribute description to a variable in an external JavaScript function. It works ok when inside the HTML page but will not work in the external script as the variable I am assigning tests out as undefined.
function NewFunction() {
var x = document.getElementById("Year").href;
//var x="hello"
if (x === undefined) {
alert("x is undefined");
} else {
alert("x is defined");
}
document.getElementById("demo").innerHTML = x;
I can change demo if I use the var x="hello". However if I try to assign x the document.getElementById("Year").href it reports back as undefined. This code works well inside the source page as a local script.
I am missing something as it seems you cannot assign a variable, information read from the HTML page.
What am I missing? Thanks
Likely problem in the time moment when script is loaded. Just call your function when DOM is ready ( see event DOMContentLoaded for more info).
document.addEventListener("DOMContentLoaded", function(event) {
NewFunction()
});
Below is your code ( with func calling on DOM Ready ) and everything seems to work fine. Try to compare with our actual code.
function NewFunction() {
var x = document.getElementById("Year").href;
//var x="hello"
if (x === undefined) {
alert("x is undefined");
} else {
alert("x is defined");
}
document.getElementById("demo").innerHTML = x;
};
document.addEventListener("DOMContentLoaded", function(event) {
NewFunction()
});
<a href='123' id='Year'>123</a>
<p id='demo'>123</p>
Good Luck !
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