When there are multiple widgets with the same name on the page, what do you do first? Determine the length? Indeed, from the strict perspective of the program, we need to judge the length, and there are two reference methods: length and no length. Let's look at this:
OEle = document. all. aaa; // There is an aaa object, but we don't know how long it is, so we can't operate on it. therefore, we need to judge the length first. as follows:
If (oEle. length) {} else {};
In either case, the content in curly braces is written differently:
The Code is as follows:
If (oEle. length ){
For (var I = 0; I OEle [I]. value ........
}
}
Else {
OEle. value ........
};
But is writing like this too complicated? When there are many codes in curly braces, We need to write the code twice ~
Fortunately, there is the document. getElementsByName () method. It processes the same for one or more objects. We can use:
OEle = document. getElementsByName ('aaa') to reference
When there is only one oEle, It is oEle [0]. When there are multiple oEle, it is very easy to use the subscript method oEle [I] to obtain them cyclically?
It is worth mentioning that it is equally valid for Name and ID.
However, it can only be applied to document objects. There is another method to apply a wider range of objects:
GetElementsByTagName, for example ......
I want to take all the input in the DIV, so that I can write it: aaa. getElementsByTagName ('input'), so that it is effective and can be different from other DIV (for example, there is a DIV called bbb, which contains the same INPUT.
Corresponds to getElementsByTagName, and there is a document. body. all. tags (). The objects using this method are much smaller than getElementsByTagName, but more than getElementsByName.
At this point, we also need to mention getElementById, which can only be used by the document Object and returns the first element of the array. Haha, its method names are all written as getElement rather than getElements. Therefore, never be confused.