Javascript getting started Article 7 js dom instance operations page 1/2

Source: Internet
Author: User

Start with the method:
1. delete a node. RemoveChild ():
<Body>
<Div id = "cssrain">
<Div id = "a"> a </div>
<Div id = "B"> B </div>
<Div id = "c"> c </div>
</Div>
</Body>
<Script>
Var msg = document. getElementById ("cssrain ");
Var B = document. getElementById ("B ");
Msg. removeChild (B );
</Script>
If you do not know the parent node of the node to be deleted? You can use the parentNode attribute.
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 B = document. getElementById ("B ");
Var c = B. parentNode;
C. removeChild (B );
</Script>

2. Replace the node. RepalceChild ()
Element. repalceChild (newNode, oldNode); // The new node is a guest and must be served first .. The oldNode must be a subnode of the Element.
Example:
<Body>
<Div id = "cssrain">
<Div id = "a"> a </div>
<Div id = "B"> B </div>
<Div id = "c"> c </div>
</Div>
</Body>
<Script>
Var cssrain = document. getElementById ("cssrain ");
Var msg = document. getElementById ("B ");
Var para = document. createElement ("p ");
Cssrain. replaceChild (para, msg );
</Script>

3. Search for 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 () is used to find all elements of a 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 ");
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.