3, Find nodes
Compared with the above method, it is relatively simple to search for nodes.
Because many people have used it. (Remember that the first sentence I know about js is getElementById ();)
GetElementById ();
Returns an object with attributes such as nodeName, nodeType, parentNode, and ChildNodes.
GetElementsByTagName ()Search for all the elements of the tag name.
Returns a set of objects that can be retrieved cyclically. Objects have attributes such as nodeName, nodeType, parentNode, and ChildNodes.
Example:
Var ps = document. getElementsByTagName ("p ");
For (var I = 0; I <ps. length; I ++ ){
Ps [I]. setAttribute ("title", "hello ");
//You can also use:Ps. item (I). setAttribute ("title", "hello ");
}
4,Set/obtain attribute nodes.
SetAttribute ();//Set
Example:
Var a = document. createElement ("p ");
A. setAttribute ("title", "my demo ");
Whether the title attribute exists or not, the subsequent value is my demo.
GetAttribute ();//Obtain
Example:
Var a = document. getElementById ("cssrain ");
Var B = a. getAttribute ("title ");
If the property does not exist, null is returned. Note that ie and ff return different values.
<Body>
<P title = "test"> aaaa </p>
<P> bbbb </p>
<Script type = "text/JavaScript">
Var paras = document. getElementsByTagName ("p ");
For (var I = 0; I <paras. length; I ++ ){
Var title_text = paras [I]. getAttribute ("title ");
If (title_text! = Null ){
//In this case, there will be a problem: ff only plays once, but ie plays twice.
//If (title_text! = "") In this way, ie only plays once, but ff pops up twice.
//What if I write it like this? If (title_text), we found that ie only plays once and ff only pops up once.
// If (title_text)This is what we want.
//Note: If ff does not exist, null is returned.
// IeReturn "";
Alert (title_text );
}
}
</Script>
</Body>
Although the returned results are different, you can use a method to judge them.
If (a. getAttribute ("title ")){
// Do something
}
5, hasChildNodes:
The name indicates whether the element has subnodes.
Returns the boolean type.
Text nodes and attribute nodes cannot have subnodes, so their hasChildNodes always return false;
HasChildNodesIt is often used with childNodes.
For example:
<Body>
<Div id = "cssrain">
<Div id = "a"> a </div>
<Div id = "B"> B </div>
<Div id = "c"> c </div>
</Div>
</Body>
<Script>
Var ps = document. getElementById ("cssrain ")
If (ps. hasChildNodes ){
Alert (ps. childNodes. length );
}
</Script>