Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

External JavaScript accessing html elements and assigning to a variable [duplicate]

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

like image 678
domenico fusco Avatar asked Mar 17 '26 01:03

domenico fusco


1 Answers

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 !

like image 155
Andriy Ivaneyko Avatar answered Mar 19 '26 14:03

Andriy Ivaneyko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!