JavaScript HTML DOM Elementen
- Vorige Pagina DOM Document
- Volgende Pagina DOM HTML
This chapter explains how to find and access HTML elements in an HTML page.
Finding HTML elements
通常,通过 JavaScript,您需要操作 HTML 元素。
To achieve this, you first need to find these elements. There are several ways to complete this task:
- Finding HTML elements through id
- Finding HTML elements through tag name
- Finding HTML elements through class name
- Finding HTML elements through CSS selectors
- Finding HTML elements through HTML object collection
Finding HTML elements through 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":
Voorbeeld
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
.
Finding HTML elements through tag name
This example finds all <p>
Element:
Voorbeeld
var x = document.getElementsByTagName("p");
This example finds the element with id="main" and then finds all elements within "main" <p>
Element:
Voorbeeld
var x = document.getElementById("main"); var y = x.getElementsByTagName("p");
Finding HTML elements through 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":
Voorbeeld
var x = document.getElementsByClassName("intro");
querySelectorAll() is not applicable for Internet Explorer 8 and earlier versions.
Finding HTML elements through CSS selectors
If you need to find all HTML elements that match the specified CSS selector (id, class name, type, attributes, attribute values, etc.), please use querySelectorAll()
methods.
This example returns all elements with class="intro" <p>
Element list:
Voorbeeld
var x = document.querySelectorAll("p.intro");
querySelectorAll()
Not applicable for Internet Explorer 8 and earlier versions.
Vind HTML objecten door middel van HTML object selectors
Deze voorbeeld zoekt naar het form element met id="frm1" in de forms collectie en toont alle elementwaarden:
Voorbeeld
var x = document.forms["frm1"]; var text = ""; var i; for (i = 0; i < x.length; i++) { text += x.elements[i].value + "<br>"; } document.getElementById("demo").innerHTML = text;
De volgende HTML objecten (en objectcollecties) zijn ook toegankelijk:
- Vorige Pagina DOM Document
- Volgende Pagina DOM HTML