user3316920
user3316920

Reputation:

Cant get it to show text from an array to the html

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

Answers (2)

luiso1979
luiso1979

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

  1. Use the onReady method of jQuery
  2. window.onload = myOnloadFunc
  3. And putting your JS at the bottom, even if this is not a guarantee.

Tell me if you are still having problems,

Regards,

Upvotes: 0

Lee Kowalkowski
Lee Kowalkowski

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

Related Questions