简体   繁体   中英

Javascript won't find my div

I have HTML file with a div and a javascript file that uses this div as a variable in a function like so:

<div id="foo"></div>

And the JS

foo = document.getElementById("foo");
function bar() {
  foo.innerHTML = "foobar"
}

But when I run bar (after load, in console) it says that bar is undefined and does not change foo.innerHTML to "foobar"

UPDATE : I call bar() in the console after the page is loaded. I also fixed the code up there

You need to update your script to

function bar() {
  document.getElementById("foo").innerHTML = "foobar"
}

There is a problem with your script. The way you are declaring your function is syntactically incorrect.

Additionally, you should make sure that when you are calling your function, the element exists in DOM.

Errors can be spotted by opening Developer Tools (F12 > Console) and fixing the respective errors

Also make sure you have your <script> tag right before the closing </body> tag in order to let JS parse the document before mapping the needed elements into DOM

That's because you invoked the script before the element was loaded.

You can either use jQuery

$(function() { /* Code goes here */ }

or vanilla JavaScript

window.onload = function() { /* Code goes here */ }

to fix this.

You need to ensure the document is loaded by the time your script runs with window.onload. And you are missing a () in your bar function:

window.onload = function(){ // we wait for the document to load
    var foo = document.getElementById("foo"); // now we are sure the div exists
    function bar() { // note the missing ()
        document.getElementById("foo").innerHTML = "foobar"
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM