JavaScript Output-tutorial
JavaScript can display output in several ways depending on where and how it runs.
Lets look at the most common methods to show results on a webpage.
Using document.getElementById()
Output
.webp)
Using document.write()
The document.write() method writes content directly into the HTML document.
Example:
Output
.webp)
When you click 'Enter'
.webp)
Using document.getElementById()
This is the most common and recommended way to show dynamic output on a webpage.
You can access an HTML element by its id and then change its content.
Example:
You can access an HTML element by its id and then change its content.
Example:
<!DOCTYPE html><html>
<body> <h2>Welcome to Quipoin</h2> <p>Addition:</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = 2 + 6; </script></body>
</html>
Output
.webp)
This method keeps your HTML and JavaScript nicely organized and is widely used in modern web development.
Using document.write()
The document.write() method writes content directly into the HTML document.
Note: Using document.write() after the page has loaded will overwrite the whole document, so it’s rarely used in modern projects.
Example:
<!DOCTYPE html><html>
<body> <h2 style="color:green">Welcome to Quipoin</h2> <p>Addition:</p> <button type="button" onclick="document.write(2 + 6)">Enter</button></body>
</html>
Output
.webp)
When you click 'Enter'
.webp)
Key Point
- Use document.getElementById() to change or display content safely inside HTML elements.
- Avoid document.write() on interactive pages because it can erase your content.
- These methods help make your web pages dynamic and interactive.