Joshua Joshua - 7 months ago 11
Javascript Question

document.getElementById ( )

I am using the w3school.com JavaScript compiler to test basic programs as I go along learning JavaScript.

The first thing I have noticed is in the following snippet:

<!DOCTYPE html>

<html>
<body>

<h1>My First Web Page</h1>
<p>My first paragraph</p>
<p id = "demo"></p>

<script>

var x = 4;
var y = 8;
var z = x + y;
var car = "Fiat";

document.getElementById("demo").innerHTML = z;
//document.getElementById("demo").innerHTML = car;

</script>

</body>
</html>


When I uncomment the second
document.getElementById
the first one (
12
) is no longer displayed; i.e. only
Fiat
is shown. Why is that? How do I simply display more than one variable content?

Answer

Simple string concatenation

document.getElementById("demo").innerHTML = z + '<br/>' + car;

or

document.getElementById("demo").innerHTML = z;
document.getElementById("demo").innerHTML += '<br/>' + car;

FYI : Updating innerHTML property is not a good idea to use since it will regenerate all html elements and it will remove the all attached event handlers to the inner elements. So be cautious while using it.