X
HOME HTML CSS JAVASCRIPT SQL PHP JQUERY ANGULAR BOOTSTRAP XML ASP.NET MORE...
REFERENCES | EXAMPLES | FORUM | ABOUT

JavaScript Output


JavaScript does not have any print or output functions.

In HTML, JavaScript can only be used to manipulate HTML elements.


Manipulating HTML Elements

To access an HTML element from JavaScript, you can use the document.getElementById(id) method.

Use the "id" attribute to identify the HTML element, and innerHTML to refer to the element content:

Example

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>

<p id="demo">My First Paragraph</p>

<script>
document.getElementById("demo").innerHTML = "Paragraph changed.";
</script>

</body>
</html>

Try it Yourself »

The JavaScript statement above (inside the <script> tag) is executed by the web browser:

document.getElementById("demo") is JavaScript code for finding an HTML element using the id attribute.

innerHTML = "Paragraph changed." is JavaScript code for changing an element's HTML content (innerHTML).


In This Tutorial

Most of the time, in this tutorial, we will use the output method described above:

Writing output into a <p> element with id="demo".


Writing to The HTML Document

For testing purposes, you can use JavaScript to write directly to the HTML document:

Example

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>

<p>My first paragraph.</p>

<script>
document.write(Date());
</script>

</body>
</html>

Try it Yourself »

Note

Use document.write for testing only.
If you execute it, on a loaded HTML document, all HTML elements will be overwritten.

Example

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>

<p>My first paragraph.</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
    document.write(Date());
}
</script>

</body>
</html>

Try it Yourself »


Writing to The Console

If your browser supports debugging, you can use the console.log() method to display JavaScript values in the browser.

Activate debugging in your browser with F12, and select "Console" in the debugger menu.

Example

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>

<script>
a = 5;
b = 6;
c = a + b;
console.log(c);
</script>

</body>
</html>

Try it Yourself »


Did You Know?

Note Debugging is the process of testing, finding, and reducing bugs (errors) in computer programs.
The first known computer bug was a real bug (an insect), stuck in the electronics.



Your suggestion:

Close [X]

Thank You For Helping Us!

Your message has been sent to W3Schools.

Close [X]
Search w3schools.com:

WEB HOSTING

UK Reseller Hosting

WEB BUILDING

Download XML Editor FREE Website BUILDER Free HTML5 Templates

SHARE THIS PAGE

facebook