Home >Web Front-end >JS Tutorial >Introduction to document object in js
Introduction to the Document object in JavaScript and code examples
Introduction:
In JavaScript, the Document object is an interface that represents the entire HTML document. It provides How to access and operate the documentation. This article will introduce the common methods and properties of the Document object and provide some specific code examples.
<html> <body> <h1 id="myHeading">Hello, World!</h1> <script> var heading = document.getElementById("myHeading"); heading.innerHTML = "Hello, JavaScript!"; </script> </body> </html>
In the above code, the element node with the id "myHeading" is obtained through the getElementById method, and the innerHTML attribute is used to change its content to "Hello, JavaScript! ".
<html> <body> <ul> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> </ul> <script> var listItems = document.getElementsByTagName("li"); for (var i = 0; i < listItems.length; i++) { listItems[i].style.color = "red"; } </script> </body> </html>
In the above code, all li element nodes are obtained through the getElementsByTagName method, and the text color of each li element is changed to red through a for loop.
<html> <body> <div id="myDiv"></div> <script> var newElement = document.createElement("p"); newElement.innerHTML = "This is a new paragraph."; document.getElementById("myDiv").appendChild(newElement); </script> </body> </html>
In the above code, a new p element node is created through the createElement method and added to the div element with the id "myDiv" using the appendChild method. .
Summary:
This article introduces some common methods and properties of Document objects in JavaScript, including getElementById, getElementsByTagName, createElement and appendChild. Through these methods and properties, you can easily access and operate the element nodes of HTML documents. I hope the code examples provided in this article will be helpful to readers who are learning and using JavaScript.
The above is the detailed content of Introduction to document object in js. For more information, please follow other related articles on the PHP Chinese website!