Document: three methods to get objects. document: Get objects
There are several common methods in Document object, which we mentioned in Dom introduction. The most common method for obtaining javascript objects is getElementById, which is one of the most common methods for obtaining objects in Document, there are also two common methods to get objects: getElementsByTagName and getElementsByName. GetElementById obtains a single object, while getElementsByName and getElementsByTagName obtain a set.
Now we have a form with the content
<Html>
Next, we can get the hyperlink address corresponding to Baidu in three ways.
GetElementsByTagName
Obtains an object set based on the tag element name.
If the above Code does not contain the name and id attributes, we can only judge by tagName.
View code
<Html>
By document. getElementsByTagName ("A"); obtains the hrefs Element Set, traverses hrefs, and compares the content of each item. If it is "Baidu", the break jumps out of the loop.
The preceding debugging method shows the hrefs Element Set obtained by the getElementsByTagName method.
Hrefs has the length attribute, which refers to the number of objects contained in the set. A useful method item () in the method is to obtain elements based on the sequence number of the elements.
GetElementsByName
Obtains an object set based on the name attribute.
At this time, the obtained object must have the name attribute.
<Html>
The Processing Method of the set obtained through getElementsByName is the same as that of getElementsByTagName.
GetElementById
Obtain the object based on the element id.
We add the id attribute to each hyperlink in the above Code, and the code becomes the sample code we saw at the beginning.
<Html>
At this time, we can see that the id attribute value of The Link corresponding to baidu is baidu. We can directly use getElementById to obtain this hyperlink object.
<script><!--getElementById-->var href1 = document.getElementById("baidu");alert(href1.href);</script>
In summary, getElementById is the most direct way to get objects and the most efficient way. However, if the element does not have the id attribute but has the name attribute, you can use getElementsByName to retrieve the object set and traverse every object in the set. If the element does not have the name attribute, you can only use getElementsByName to retrieve the object.