Reputation: 1031
I'm trying to update the innerHTML for a div tag and maybe something is wrong in the simple application here:
<!DOCTYPE html>
<html lang="en" xmlns=""http://www.w3.org/1999/xhtml"">
<head>
<title>Test</title>
<script>
var element = document.getElementById("aaa");
element.innerHTML = "1";
</script>
</head>
<body>
<div id="aaa">aaa</div>
</body>
</html>
I want the "aaa" to be "1" when I see it in a browser.
any idea?
thanks
Upvotes: 0
Views: 2980
Reputation: 6565
Try this
<body>
<div id="aaa">aaa</div>
<script>
var element = document.getElementById("aaa");
element.innerHTML = "1";
</script>
</body>
script code should be executed after loading tag with name 'aaa'
Else use onload
event function to call the code
Upvotes: 0
Reputation: 7768
<!DOCTYPE html>
<html lang="en" xmlns=""http://www.w3.org/1999/xhtml"">
<head>
<title>Test</title>
</head>
<body>
<div id="aaa">aaa</div>
</body>
<script>
var element = document.getElementById("aaa");
element.innerHTML = "1";
</script>
</html>
Work only after element loaded
Upvotes: 0
Reputation: 8836
Try using
<script>
window.onload = function(){
document.getElementById("aaa").innerHTML = "1";
}
</script>
Upvotes: 0
Reputation: 36487
On the first look your code is perfectly fine, there's just some tiny problem with it:
Javascript code is executed the moment the parser hits the code block. This results in your code being executed before the actual body of the document is constructed, resulting in element
being undefined
rather than pointing to the correct <div>
.
To solve this issue, wrap your code in a function and then call it in the onload
event of <body>
, which will be executed once everything is loaded.
Upvotes: 0
Reputation: 388316
It is because when your script is executed the element aaa
is not yet added to the dom.
The safer method to do dom manipulation is to do it after the dom is loaded, for that you can use the onload event handler.
Another tip related to html loading is to place all the scripts at the bottom of the page.
You need to move your script to on load
<html lang="en" xmlns=""http://www.w3.org/1999/xhtml"">
<head>
<title>Test</title>
<script>
window.onload = function(){
var element = document.getElementById("aaa");
element.innerHTML = "1";
}
</script>
</head>
<body>
<div id="aaa">aaa</div>
</body>
</html>
Upvotes: 2
Reputation: 145388
At the moment your script is executing, there is no #aaa
element visible for JavaScript.
The good practice is to put your <script>
tag right before </body>
, so the script will be executed when all the document is loaded:
<!DOCTYPE html>
<html lang="en" xmlns=""http://www.w3.org/1999/xhtml"">
<head>
<title>Test</title>
</head>
<body>
<div id="aaa">aaa</div>
<script>
var element = document.getElementById("aaa");
element.innerHTML = "1";
</script>
</body>
</html>
Upvotes: 2