Adding text to element with InnerHTML

Hello, im trying to add a name of fruit to already existing row of fruits in paragraph with push property with innerHtml or how should i better call this functionality on web?
Here’s my HTML from Jsfiddle:

<!doctype html>
<html>
<head>
</head>
<body>
<p id="demo">
Bananas, Oranges, Apples
</p>
<button onclick="myFunction()">Try it
</button>
</body>
</html>

My JavaScript:

function myFunction() {
 
 document.getElementById("demo").innerHtml = push("Kiwi");

}

Am i missing something? What are best ways to do it?

When ever i click the button it doesnt change at all, no name added.

Hey, push() is an array method and your text isn’t an array. You can add to innerHTML just by using += ‘Kiwi’.

1 Like

Your code should look like this:

function myFunction() {
 document.getElementById("demo").innerHTML = "Bananas, Oranges, Apples, Kiwi";
}

“push” won’t do anything, because innerHTML takes a string of text as input. In some cases, that string of text might be HTML code itself, but you should never try to put JavaScript in there, because it won’t do anything. It should be either straight text or HTML only.

1 Like