JavaScript HTML DOM
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 Document Object Model of the page.
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.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body> <p id="intro">你好世界!</p> <p>该实例展示了 <b>getElementById</b> 方法!</p> <script> x=document.getElementById("intro"); document.write("<p>文本来自 id 为 intro 段落: " + x.innerHTML + "</p>"); </script> </body> </html>
If the element is found, the method returns the element as an object (in x).
If the element is not found, x will contain null.
Find HTML elements by tag name
This example finds the element with id="main", and then finds all <p> elements in the element with id="main":
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body> <p>你好世界!</p> <div id="main"> <p> DOM 是非常有用的。</p> <p>该实例展示了 <b>getElementsByTagName</b> 方法</p> </div> <script> var x=document.getElementById("main"); var y=x.getElementsByTagName("p"); document.write('id="main"元素中的第一个段落为:' + y[0].innerHTML); </script> </body> </html>
Find HTML elements through class names
This example uses the getElementsByClassName function to find elements with class="intro":
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body> <p class="intro">你好世界!</p> <p>该实例展示了 <b>getElementsByClassName</b> 方法!</p> <script> x=document.getElementsByClassName("intro"); document.write("<p>文本来自 class 为 intro 段落: " + x[0].innerHTML + "</p>"); </script> <p><b>注意:</b>Internet Explorer 8 及更早 IE 版本不支持 getElementsByClassName() 方法。</p> </body> </html>