JavaScript Output
JavaScript has no built-in print or output function.
JavaScript displaying data
JavaScript can output data in different ways:
- Use window.alert() Pop up an alert box.
- Use document.write() The method writes content to the HTML document.
- Use innerHTML Write to an HTML element.
- Use console.log() Write to the browser console.
Using window.alert()
You can pop up an alert box to display data:
Example
<
!DOCTYPE
html
<
html
<
body
<
h1My first page
<
/h1
<
pMy first paragraph.
<
/p
<
scriptwindow.alert(5 + 6);
<
/script
<
/body
<
/htmlTry it »
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 get or insert the element's content:
Example
<
!DOCTYPE
html
<
html
<
body
<
h1My first web page
<
/h1
<
p
id=
"demo"My first paragraph
<
/p
<
scriptdocument.getElementById("demo").innerHTML = "Paragraph changed.";
<
/script
<
/body
<
/htmlTry it »
The above JavaScript statement (in