Home > Article > Web Front-end > 【JavaScript Tutorial】JavaScript Output
JavaScript Output
JavaScript does not have any printing or output functions.
In HTML, JavaScript is usually used to manipulate HTML elements.
Manipulate 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:
Example
<!DOCTYPE html> <html> <body> <h1>我的第一个 Web 页面</h1> <p id="demo">我的第一个段落</p> <script> document.getElementById("demo").innerHTML = "段落已修改。"; </script> </body> </html>
The above JavaScript statement (in the 3f1c4e4b6b16bbbd69b2ee476dc4f83a tag) can be executed in a web browser :
document.getElementById("demo") is JavaScript code that uses the id attribute to find HTML elements.
innerHTML = "Paragraph changed." is the JavaScript code used to modify the HTML content (innerHTML) of the element.
In this tutorial
In most cases, in this tutorial, we will use the method described above to output:
The following example writes the e388a4556c0f65e1904146cc1a846bee element with id="demo" directly to HTML In document output:
Write to HTML document
For testing purposes, you can write JavaScript directly in the HTML document:
Example
<!DOCTYPE html> <html> <body> <h1>我的第一个 Web 页面</h1> <p>我的第一个段落。</p> <script> document.write(Date()); </script> </body> </html>
Please use document.write() to only write content to the document output.
If you execute document.write after the document has finished loading, the entire HTML page will be overwritten.
Instance
<!DOCTYPE html> <html> <body> <h1>我的第一个 Web 页面</h1> <p>我的第一个段落。</p> <button onclick="myFunction()">点我</button> <script> function myFunction() { document.write(Date()); } </script> </body> </html>
Written 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.
Example
<!DOCTYPE html> <html> <body> <h1>我的第一个 Web 页面</h1> <script> a = 5; b = 6; c = a + b; console.log(c); </script> </body> </html>
Did you know?
Debugging in a program is the process of testing, finding and reducing bugs (errors).
The above is the content output by JavaScript in [JavaScript Tutorial]. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!