Through the HTML DOM, all elements of the JavaScript HTML document can be accessed.
HTML DOM (Document Object Model)
When a web page is loaded, the browser creates the page's Document Object Model (Document Object Model).
The HTML DOM model is constructed as a tree of objects.
HTML DOM tree
Through the programmable object model, JavaScript has gained enough power to create dynamic HTML.
JavaScript can change all HTML elements in the page
JavaScript can change all HTML attributes in the page
JavaScript can change all CSS styles in the page
JavaScript is able to react to all events in the page
Find HTML elements
Usually, with JavaScript, you need to manipulate HTML elements.
In order to do this, you must first find the element. There are three ways to do this:
Find the HTML element by id
Find the HTML element by tag name
Find the HTML element by class name
Finding HTML elements by id
The simplest way to find HTML elements in the DOM is by using the element's id.
Example
This example looks for the element with id="intro":
[html] view plain copy <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "m.sbmmt.com/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="m.sbmmt.com/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> </head> <body> <p id="intro">hello</p> <p>本例演示 <strong>getElementById</strong> 方法</p> <script> x = document.getElementById("intro"); document.write('<p>id="intro" 的段落中的文本是:' + x.innerHTML + '</p>'); </script> </body> </html>
If the element is found, the method will return it as an object (in x) element.
If the element is not found, x will contain null.
Find HTML elements by tag name
Example
This example finds the element with id="main", and then finds all
elements in "main":
[html] view plain copy <html xmlns=m.sbmmt.com/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> </head> <body> <div id="main"> <p>The DOM is very useful.</p> <p>本例演示 <b>getElementsByTagName</b> 方法。</p> </div> <script> var x = document.getElementById("main"); var y = document.getElementsByTagName("p"); document.write('id 为 "main" 的 div 中的第一段落文本是:' + y[0].innerHTML); </script> </body> </html>
Finding HTML elements by class name does not work in IE 5,6,7,8.
【Related recommendations】
1. Free html online video tutorial
3. php.cn original html5 video tutorial
The above is the detailed content of Example code for using HTML DOM to access JavaScript document elements. For more information, please follow other related articles on the PHP Chinese website!