Do you know about Javascript Dom programming? In the DOM model, every element, attribute, and text can be considered as an object, and javascript can access these objects independently, you can use some methods to find and change these objects.
Javascript Dom Programming
I. Document Object Model
In the DOM model, each element (element), attribute), and text can be viewed as an object. javascript can access these objects independently, you can use some methods to find and change these objects.
DOM stipulates that each HTML Tag is an element node, and the text contained in the element is a text node, and each HTML attribute is an attribute node.
Ii. Accessing DOM nodes
A: Get elements by ID
- vartarget=document.getElementById("berenger");
-
B: Get the element through TagName
- varlistItems=document.getElementsByTagName("li");
-
ListItems is an array-like object. You can use listItems. Length to obtain the object Length.
C: Get the element through ClassName
In most cases, it is easier to use className to obtain elements than tagname in Javascript Dom programming. However, dom does not provide corresponding functions, so we need to create a method.
It can be divided into the following three steps:
1: search for all elements in the document.
2: For each element, compare the class to be searched.
3: if they are the same, add them to the list.
The js Code is as follows:
- VarCore = {};
-
- Core. getElementsByClass = function (theClass)
- {
- VarelementArray = [];
- // GetElementsByTagName ("*") is not supported in IE, and document. All is used.
- If (document. all)
- {
- ElementArray = document. all;
- }
- Else
- {
- ElementArray = document. getElementsByTagName ("*");
- }
- VarmatchedArray = [];
- Varpattern = newRegExp ("(^ |)" + theClass + "(| $ )");
- For (vari = 0; I <elementArray. length; I ++)
- {
- If (pattern. test (elementArray [I]. className ))
- {
- MatchedArray [matchedArray. length] = elementArray [I];
- }
- }
- ReturnmatchedArray;
- };
-