JavaScript output

JavaScript Output

JavaScript is typically used to manipulate HTML elements.

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 to an HTML document. Use innerHTML to write to HTML elements. Use console.log() to write to the browser's console.

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:

<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p id="demo">My First Paragraph</p>
<script>document.getElementById("demo").innerHTML="My First JavaScript";</script>
</body>
</html>

##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 HTML elements.

innerHTML = "Paragraph has been modified." is the JavaScript code used to modify the HTML content (innerHTML) of the element.

Use window.alert()

You can pop up an alert box to display data:

<!DOCTYPE html>
<html>
<body>
<h1>我的第一个页面</h1>
<p>我的第一个段落。</p>
<script>
window.alert('Hello Word!');
</script>
</body>
</html>

In this tutorial

In most cases, in this tutorial we will use the method described above to output:

The following example directly writes the <p> element with id="demo" to the HTML document output:

Write to HTML document

For testing purposes, you can JavaScript is written directly in the HTML document:

<!DOCTYPE html>
<html>
<body>
<h1>我的第一个 Web 页面</h1>
<p>我的第一个段落。</p>
<script>
document.write(Date());
</script>
</body>
</html>


Please use document.write() to only output the written content to the document.

If document.write is executed after the document has finished loading, the entire HTML page will be overwritten.

 <!DOCTYPE html>
<html>
<body>
<h1>我的第一个 Web 页面</h1>
<p>我的第一个段落。</p>
<button onclick="myFunction()">点我</button>
<script>
function myFunction()  {
   document.write(Date());
}
</script>
</body>
</html>


Write to console

If your browser supports debugging, you can use console The .log() method displays 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>
<body>
<h1>我的第一个 Web 页面</h1>
<script>
a = 5;
b = 6;
c = a + b;
console.log(c);
</script>
</body>
</html>

Debugging in a program is the process of testing, finding and reducing bugs (errors).


Continuing Learning
||
<!DOCTYPE html> <html> <body> <h1>我的第一个页面</h1> <p>我的第一个段落。</p> <script> window.alert('Hello Word!'); </script> </body> </html>
submitReset Code
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!