JavaScript Output
- Depending on the environment in which it's executed, javascript can produce output in various ways.
Methods for Producing Output in JavaScript:
Document.getElementById():
- In web development, JavaScript is often used to manipulate the HTML document. You can change the content of HTML elements, create new elements, or modify the attributes of existing elements.
<p id="output">This is some text.</p>
<script>
var outputElement = document.getElementById("output");
outputElement.textContent = "This text is updated by JavaScript.";
</script>
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:
document.write():
- You can write content directly to the HTML document using methods like document.write()
- this approach is less commonly used because it can overwrite the entire document and isn't typically recommended for modern web development.
Example:
<!DOCTYPE html>
<html>
<body>
<h2 style="color:red">Welcome to quipoin</h2>
<p>Addition.</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 2 + 6;
</script>
</body>
</html>
Output:
Using document.write() after an HTML document is loaded, will delete all existing HTML:
Example:
<!DOCTYPE html>
<html>
<body>
<h2 style="color:green">My Welcome to Quipoin</h2>
<p> Adittion</p>
<button type="button" onclick="document.write(2 + 6)">Enter</button>
</body>
</html>
Output:
on clicking Enter we get 8