0

i'm trying to use javascript to add new content on a button click.

I have got the javascript to work if the button is clicked once but i would like to have it so every time i press the button a new 'hello world' will be created.

<button id="myBtn">Try it</button>

 <p><strong>Note:</strong> The addEventListener() method is not 
 supported in     Internet Explorer 8 and earlier versions.</p>

 <p id="demo"></p>

 <script>
 document.getElementById("myBtn").addEventListener("click", function(){
 document.getElementById("demo").innerHTML = "Hello World";
 });
 </script>

Thanks in advance

1
  • Sorry, accidentally clicked it. Thanks for heads up Commented Sep 29, 2015 at 19:53

1 Answer 1

4

Change:

document.getElementById("demo").innerHTML = "Hello World";

to:

document.getElementById("demo").innerHTML += "Hello World";

Using = will set the content on each click, overwriting what was there before. Using += will concatenate the text to what was there before.

 document.getElementById("myBtn").addEventListener("click", function() {
   document.getElementById("demo").innerHTML += "Hello World ";
 });
<button id="myBtn">Try it</button>

<p><strong>Note:</strong> The addEventListener() method is not supported in Internet Explorer 8 and earlier versions.</p>

<p id="demo"></p>

Sign up to request clarification or add additional context in comments.

1 Comment

I want to use a button for the onClick as opposed to using the actual text

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.