Reputation:
My problem is that I can't get Javascript to change the text in an HTML p
tag.
I got this HTML button
with id="knap"
and I got this p
tag with id="answer"
. I want that if user clicks on the button, then the text in "answer" will change.
In the Javascript code, I got an array carrying all the answers:
I got the following code – never tried Javascript, but have programmed in other languages –:
(Im using an external JS document)
var answer = [
"answer1",
"answer2",
"answer3",
"answer4"
];
document.getElementById("knap").onclick = function() {
var panel = document.getElementById("answer");
panel.innerHTML = answer[1];
}
This is my html button:
<a class="button" href="#">
<div id="knap">
<h1>Something</h1>
</div>
</a>
How to fix it?
Demo : http://jsfiddle.net/84vJg/
Upvotes: 0
Views: 128
Reputation: 917
Take a look at what i did here, it works.
I just used this html, and as you would see I used your JS code.
<a id="knap" href="#">KNAP</a>
<p id="answer"></p>
I think your problem is related with the way a web page is loaded.
The JS code is loaded asynchronously, so it may happen the your DOM isn't loaded yet when the JS is executed. To ensure your DOM is loaded, you could use several mechanisms
Tell me if you are still having problems,
Regards,
Upvotes: 0
Reputation: 11751
Your javascript looks fine, unless you're running it before your HTML has been parsed, i.e. document.getElementById("knap")
returns null/undefined.
Are you including your HTML before or after your SCRIPT? Put your script after your HTML and it should work.
Upvotes: 1