Every HTML document loaded into the browser will become a Document object. The Document object allows us to access all elements in the HTML page from scripts.
Properties
1 document.anchors Returns references to all Anchor objects in the document. There are also document.links/document.forms/document.images, etc.
2 document.URL Returns the url of the current document
3 document.title Returns the title of the current document
4 document.body Returns the body element node
Method
1 document.close() Closes the output stream opened with the document.open() method and displays the selection The data.
<!DOCTYPE html> <html> <head> <script> function createDoc() { var w=window.open(); w.document.open(); w.document.write("<h1>Hello World!</h1>"); w.document.close(); } </script> </head> <body> <input type="button" value="New document in a new window" onclick="createDoc()"> </body> </html>
2 document.createElement() Create an element node.
<!DOCTYPE html> <html lang="en"> <!DOCTYPE html> <head> </head> <body> <p>hello world</p> <script> var a = document.createElement('hr'); document.body.appendChild(a) </script> </body> </html>
3 document.createAttribute() Create an attribute node.
<!DOCTYPE html> <html> <body> <p id="demo">Click the button to make a BUTTON element.</p> <button onclick="myFunction()">Try it</button> <script> function myFunction() { var btn=document.createElement("BUTTON"); document.body.appendChild(btn); }; </script> </body> </html>
4 document.createTextNode() Create a text node.
<!DOCTYPE html> <html lang="en"> <!DOCTYPE html> <head> </head> <body> <p>hello world</p> <script> var a = document.createTextNode('hahahah'); document.body.appendChild(a) </script> </body> </html>
5 document.getElementsByClassName() Returns a collection of all elements with the specified class name in the document as a collection of NodeList objects. The so-called NodeList object collection is a data format similar to an array. It only provides the length attribute, and the push and pop methods in the array are not provided.
6 document.getElementById() returns a reference to the first object with the specified id.
7 document.getElementsByName() returns a collection of objects with the specified name.
8 document.getElementsByTagName() returns a collection of objects with the specified tag name.
9 document.write() writes HTML expressions or JavaScript code to the document. Note: Using the write method after the HTML document is loaded will cause the write content to overwrite the original HTML document.
<!DOCTYPE html> <html lang="en"> <!DOCTYPE html> <head> </head> <body> <p>hello world</p> <script> document.write('hahahh') </script> </body> </html>
The above is the detailed content of Detailed explanation of javascript document object properties and method code examples. For more information, please follow other related articles on the PHP Chinese website!