Categories
JavaScript Web development

JavaScript Output

JavaScript Output defines the ways to display the output of a given code. JavaScript can “display” data in different ways:  

a) Writing into an HTML element, using innerHTML.

b) Writing into the HTML output using the document.write()

c) Writing into an alert box, using a window.alert().

d) Writing into the browser console, using console.log().

JavaScript output

a) Using innerHTML

To access an HTML element, JavaScript can use the document.getElementbyId(id) method. The id attribute defines the HTML element. The innerHTML property defines the HTML content:

Example:

<!DOCTYPE html>
<html>
<body>

<h4>This is an HTML heading.</h4>
<p>This is a paragraph.</p>

<p id="js-1"></p>

<script>
document.getElementById("js-1").innerHTML = 5 + 6;
</script>

</body>
</html> 

Output:

This is an HTML heading.

This is a paragraph.


Changing the innerHTML property of an HTML element is a common way to display data in HTML.

b) Using document.write()

For testing purposes, it is convenient to use the document.write():

Example:

<!DOCTYPE html>
<html>
<body>

<h4>This is an HTML heading</h4>
<p>This is a paragraph.</p>

<script>
document.write(5 + 6);
</script>

</body>
</html>    

Output:

This is an HTML heading

This is a paragraph.

11

Note: The document.write() method should only be used for testing. 

c) Using window.alert()

You can use an alert box to display data:

<!DOCTYPE html>
<html>
<body>

<h4>This is an HTML heading </h4>
<p>This is a paragraph.</p>

<script>
window.alert(5 + 6);
</script>

</body>
</html> 

Output:

JavaScript Output

d) Using console.log()

For debugging purposes, you can use the console.log() method to display data: 

<!DOCTYPE html>
<html>
<body>

<h4>Press F12</h4>

<p>Select "Console" in the debugger menu. Then click Run again.</p>

<script>
console.log(5 + 6);
</script>

</body>
</html> 

Output:

JavaScript Output

Enjoy!