Search code examples
javascriptbreakline-breaks

JavaScript <br /> doesn't work


I'm trying to insert a line breaker into javascript file to automatically add into html tag. I searched on google, but couldn't get any info on how to do it properly.

Screenshot: screenshot

(function() {
	
	//Array of cars
	var car = ['Dodge', 'Nissan', 'Honda', 'Ford', 'Ferrari', 'Lamborghini', 'Audi', 'Porsche', 'Maserati', 'Bentley'];
	//Length of array
	var arrayLength = car.length;
	//Message
	var msg = '';

	//Loop through the items in the array
	for (var i = 0; i < arrayLength; i++) {
		//Current car to the message
		msg += "The car is: " + car[i] + "<br />";
	}

	//Upading HTML
	var el = document.getElementById("car");
	el.textContent = msg;
	
}());
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<link rel="stylesheet" type="text/css" href="../../../css/style.css">
</head>
<body>
	<div class="wrapper">
	<header>
		<h1>Page 5</h1>
	</header>
	<h2 id="car">Getting stuff from javascript with id="car"</h2>
	<footer>
	</footer>
	<script src="05.js"></script>
	</div>
</body>
</html>


Solution

  • You need to use innerHTML to be able to insert <br/> wish is an html tag

    (function() {
    	
    	//Array of cars
    	var car = ['Dodge', 'Nissan', 'Honda', 'Ford', 'Ferrari', 'Lamborghini', 'Audi', 'Porsche', 'Maserati', 'Bentley'];
    	//Length of array
    	var arrayLength = car.length;
    	//Message
    	var msg = '';
    
    	//Loop through the items in the array
    	for (var i = 0; i < arrayLength; i++) {
    		//Current car to the message
    		msg += "The car is: " + car[i] + "<br />";
    	}
    
    	//Upading HTML
    	var el = document.getElementById("car");
    	el.innerHTML = msg;
    	
    }());
    <!DOCTYPE html>
    <html lang="en">
    <head>
    	<meta charset="utf-8">
    	<link rel="stylesheet" type="text/css" href="../../../css/style.css">
    </head>
    <body>
    	<div class="wrapper">
    	<header>
    		<h1>Page 5</h1>
    	</header>
    	<h2 id="car">Getting stuff from javascript with id="car"</h2>
    	<footer>
    	</footer>
    	<script src="05.js"></script>
    	</div>
    </body>
    </html>