JavaScript does not have any printing or output functions.
JavaScript displays data
JavaScript can output data in different ways:
Use window.alert() to pop up Warning box.
Use the document.write() method to write content into an HTML document.
Use innerHTML to write to HTML elements.
Use console.log() to write to the browser's console.
Use window.alert()
You can pop up an alert box to display data:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>PHP中文网(php.cn)</title> </head> <body> <h1>我的第一个页面</h1> <p>我的第一个段落。</p> <script> window.alert('你好吗'); </script> </body> </html>
Run the program to try it
Manipulating HTML Elements
To access an HTML element from JavaScript, you can use the document.getElementById(id) method.
Please use the "id" attribute to identify HTML elements, and innerHTML to get or insert element content:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>PHP中文网(php.cn)</title> </head> <body> <h1>PHP中文网</h1> <p id="demo">我的第一个段落。</p> <script> document.getElementById("demo").innerHTML="段落已修改。"; </script> </body> </html>
Run the program to try it
The above JavaScript statement (in < script> tag) can be executed in a web browser:
document.getElementById("demo") is JavaScript code that uses the id attribute to find an HTML element.
innerHTML = "Paragraph has been modified." is the JavaScript code used to modify the HTML content (innerHTML) of the element.
Write to HTML document
You can write JavaScript directly in HTML document:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>PHP中文网(php.cn)</title> </head> <body> <h1>我的第一个 Web 页面</h1> <p>我的第一个段落。</p> <script> document.write(Date()); </script> </body> </html>
Run the program to try it out
Note: Please use document.write() to only write content to the document output. If document.write is executed after the document has finished loading, the entire HTML page will be overwritten. Just like the following
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>PHP中文网(php.cn)</title> </head> <body> <h1>我的第一个 Web 页面</h1> <p>我的第一个段落。</p> <button onclick="myFunction()">点我</button> <script> function myFunction() { document.write(Date()); } </script> </body> </html>
Run the program and try it
Write to the console
If your browser supports debugging , you can use the console.log() method to display JavaScript values in the browser.
Use F12 in the browser to enable debugging mode, and click the "Console" menu in the debugging window.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>PHP中文网(php.cn)</title> </head> <body> <h1>我的第一个 Web 页面</h1> <p> 浏览器中(Chrome, IE, Firefox) 使用 F12 来启用调试模式, 在调试窗口中点击 "Console" 菜单。 </p> <script> a = 5; b = 6; c = a + b; console.log(c); </script> </body> </html>
Run the program and try it