Joshua Joshua - 1 year ago 57
Javascript Question

document.getElementById ( )

I am using the 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>


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


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

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



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

Answer Source

Simple string concatenation

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


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.