JavaScript: Different ways to get output

 We can get outout of JavaScript in different ways. The different ways are:

1. Writing into an  HTML element, using innerHTML

In this method, the id attribute defines the HTML element, to access this element JavaScript uses the document.getElementById(id) followed by inner.HTML, here innerHTML property defines the HTML content.

<html>

<body>

<h2>My FirstWeb Page</h2>

<p>This is my JavaScript first Paragraph.</p>

<p id="test"></p>

<script>

document.getElementById("test").innerHTML = 5 + 6;

</script>

</body>

</html> 




Output in Browser


Try it Yourself

Try it yourself editor
 
Code
Output

2. Writing into the  HTML output, using document.write().

This method is generally used for testing purpose, because when document.write() is used after an HTML document is loaded, it deletes all existing HTML.

For ex.

<html>

<body>

<h2>My First Web Page</h2>

<p>This is my JavaScript second paragraph.</p>

<button type="button" onclick="document.write(9+ 6)">Try it</button>

</body>

</html>

Try it Yourself

Try it yourself editor
 
Code
Output

Here, when we click 'document.write' button 'Try_it', It displays only onclick content (9 + 6) and deletes all the previous HTML.

3. Writing into an alert box, using window.alert().

We can use an alert box also to display data in JavaScript, whenever required.

For ex.

<html>

<body>

<h2>My First Web Page</h2>

<p>This is my JavaScript third paragraph.</p>

<script>

window.alert(5 + 95);

</script>

</body>

</html> 


Try it Yourself

Try it yourself editor
 
Code
Output

We can skip the keyword 'window'. In JavaScript, window object is the global scope object. This means that variables, properties and methods belong to the window object are by default. This also means that specifying the 'window' keyword is optional.

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

For debugging purpose, we can call the 'console.log()' method in browser to display data.
For ex:
<html>
<body>
<h2>Activate Debugging</h2>
<p>F12 on your keyboard will activate debugging.</p>
<p>Then select "Console" in the debugger menu.</p>
<p>Then click Run again.</p>
<script>
console.log(5 + 6);
</script>
</body>
</html> 

Try it Yourself

Try it yourself editor
 
Code
Output

JavaScript Print

JavaScript doesn't have any print method or print object. We can't access any output device from JavaScript.

But we can call the 'window.print()' method in the browser to print the content of the current window.

For ex:

<html>

<body>

<h2>The window.print() Method</h2>

<p>Click the button to print the current page.</p>

<button onclick="window.print()">Print this page</button>

</body>

</html>


Try it Yourself

Try it yourself editor
 
Code
Output

TOP










No comments:

Post a Comment

Python: Functions