JavaScript HTML DOM 元素
This chapter explains how to find and access HTML elements in the HTML page.
Find HTML elements
Usually, through JavaScript, you need to manipulate HTML elements.
To achieve this, you need to first find these elements. There are several ways to complete this task:
- Find HTML elements by id
- Find HTML elements by tag name
- Find HTML elements by class name
- Find HTML elements by CSS selector
- Find HTML elements by HTML object collection
Find HTML elements by id
The simplest way to find HTML elements in the DOM is to use the element's id.
This example finds the element with id="intro":
实例
var myElement = document.getElementById("intro");
If the element is found, this method will return the element as an object (in myElement).
If the element is not found, myElement will contain null
.
Find HTML elements by tag name
This example finds all <p>
Element:
实例
var x = document.getElementsByTagName("p");
This example finds the element with id="main" and then finds all elements in "main" <p>
Element:
实例
var x = document.getElementById("main"); var y = x.getElementsByTagName("p");
Find HTML elements by class name
If you need to find all HTML elements with the same class name, please use getElementsByClassName()
.
This example returns a list of all elements containing class="intro":
实例
var x = document.getElementsByClassName("intro");
querySelectorAll() kana dake Internet Explorer 8 da kude na banse no nai.
Find HTML elements by CSS selector
If you need to find all HTML elements that match the specified CSS selector (id, class name, type, attribute, attribute value, etc.), please use querySelectorAll()
method.
This example returns all elements with class="intro" <p>
Element list:
实例
var x = document.querySelectorAll("p.intro");
querySelectorAll()
kana dake Internet Explorer 8 da kude na banse no nai.
通过 HTML 对象选择器查找 HTML 对象
本例查找 id="frm1" 的 form 元素,在 forms 集合中,然后显示所有元素值:
实例
var x = document.forms["frm1"]; var text = ""; var i; for (i = 0; i < x.length; i++) { text += x.elements[i].value + "
"; } document.getElementById("demo").innerHTML = text;
以下 HTML 对象(和对象集合)也是可访问的: