1

I'm familiar with using ID's to help display your JavaScript string text onto your HTML webpage like so:

<html>
<body>
<button onClick = "display()">Press Me</button>
<p id = "text"></p>

<script>

function display() {
var string = "hello";
var message = document.getElementById("text");
message.innerHTML = string;      
}

</script>
</body>
</html>

But what if I wanted to display "hello" multiple times by the press of the button? I don't want to keep adding id's the same way I did "text" to appear. Is there anyway I could simply print out the text once you press the button for however many times you'd like in vanilla JavaScript?

Also, I am aware of "repeat()" but that's not what I'm looking for.

4
  • If I understand you correctly, If I press one time it'll show hello, if I press another time It will show another hello bellow the first one and etc? Commented Sep 7, 2020 at 22:19
  • Instead of message.innerHTML = string;, I would do like: message.textContent += string+'<br />';. I just used .textContent so HTML parsing is not an issue. It's the += that you need. Commented Sep 7, 2020 at 22:23
  • @FernandoZamperin correct, although it doesn't necessarily have to be on the next line. I was just curious on how I'd like to have the string repeat multiple times by the click of the button. Commented Sep 7, 2020 at 22:24
  • @StackSlave Thank you very much! Commented Sep 7, 2020 at 22:25

1 Answer 1

3

But what if I wanted to display "hello" multiple times by the press of the button?

It's enough to change this line:

message.innerHTML = string;  

to:

message.innerHTML += string;   // add at the end....

<button onClick = "display()">Press Me</button>
<p id = "text"></p>

<script>

    function display() {
        var string = "hello ";
        var message = document.getElementById("text");
        message.innerHTML += string;
    }

</script>

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

1 Comment

Thank you very much! I wasn't aware the addition assignment operator managed to do that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.