Common methods for manipulating DOM node elements using JavaScript (Create/delete/replace/copy, etc.)

Source: Internet
Author: User
Tags cdata manual writing tag name tagname

  1. getElementById (ID)
    This is one of the most common examples of accessing an element through an ID:
    <body>
    <div id="myid">
    test
    </div>
    <script language="javascript">
    alert(document.getElementById("myid").innerHTML);
    </script>
    </body>

    Note: If the ID of the element is not unique, then the first element of that ID name will be taken
  2. Getelementsbyname (name)
    This is done by name to get a bunch of elements (as an array), see the element behind a small s to know, ID is required in the HTML document, name can not be unique, such as CheckBox, Radio and other places will use multiple input with the same name to identify whether it is an accomplice. Yes, Getelementsbyname (name) is only used to get input, radio, checkbox and other elements, such as <input name= "MyRadio" type= "Radio"/>
  3. getElementsByTagName (tagname)   See this method to know that this is also the acquisition of a heap of elements (as an array), by TagName is the tag name to obtain. You can iterate through this array to get each individual element. When a DOM structure is large, it can be used to effectively narrow the scope of the search.  
    <script> 
    Function Test () { 
    Testall=document.getelementsbytagname ("body");  
    Testbody=testall.item (0);// Get all tagname elements (of course, only one per page)
    Testall=testbody.getelementsbytagname ("P");//Get all the P elements of the body child element
    Testnode= Testall.item (1); Get the second P element
    alert (testnode.firstChild.nodeValue);//Display the text of this element

    </script> 
    </ head> 
    <body> 
    <p>hi</p> 
    <p>hello</p> 
    < Script language= "JavaScript";
    test ();
    </script>
    </body> 
  4. AppendChild (node)
    Appends a node to the current element, which should be called the object more appropriately.
    <body>
    <div id="test"></div>
    <script type="text/javascript">
    var newdiv=document.createElement("div")
    var newtext=document.createTextNode("A new div")
    newdiv.appendChild(newtext)
    document.getElementById("test").appendChild(newdiv)
    </script>
    </body>

    Just now I was in the first example in order to show the content, using the innerHTML, just saw the article just learned that innerHTML does not belong to the DOM.
  5. RemoveChild (childreference)
    Deletes the child node of the current node and returns the node that was deleted.
    This deleted node can be inserted somewhere else.
    <body>
    <div id="parent"><div id="child">A child</div></div>
    <script language="javascript">
    var childnode=document.getElementById("child")
    var removednode=document.getElementById("parent").removeChild(childnode)
    </script>
    </body>
  6. CloneNode (deepboolean)
    copies and returns the replication node of the current node, which is an orphaned node that replicates the properties of the original node and, before adding the new node to the document, Modify the ID property as needed to ensure that its ID is unique.
    This method supports a Boolean parameter that, when Deepboolean is set to true, copies all the child nodes of the current node, including the text within that node.
    <body>
    <p id= "Mynode" >TEST</P>
    <script language= "javascript
    P=document.getelementbyid ("Mynode")
    Pclone = P.clonenode (true);
    P.parentnode.appendchild (Pclone);
    </script>
    </body>
  7. ReplaceChild (NewChild, Oldchild)
    Change one child node of the current node to another node
    <body>
    <div id="mynode2">
    <span id="orispan">span</span>
    </div>
    <script language="javascript">
    var orinode=document.getElementById("orispan");
    var newnode=document.createElement("p");
    var text=document.createTextNode("test ppp ");
    newnode.appendChild(text);
    document.getElementById("mynode2").replaceChild(newnode, orinode);
    </script>
    </body>

Property:

List of properties for 1Attributes storage nodes (read only)
List of child nodes of the 2childNodes storage node (read only)
3dataType returns the data type of this node
4Definition definition of a node given in DTD or XML Schema (read-only)
5DOCTYPE Specifies the document type node (read-only)
6documentElement returns the root element of the document (Readable and writable)
7firstChild returns the first child node of the current node (read-only)
8Implementation return Xmldomimplementation Object
9lastChild returns the last child node of the current node (read-only)
10nextSibling returns the next sibling node of the current node (read-only)
11nodeName returns the name of the node (read-only)
12nodeType returns the type of the node (read-only)
13nodeTypedValue Storage node value (readable and writable)
14nodeValue returns the text of the node (readable and writable)
15ownerDocument returns the root document containing this node (read-only)
16parentNode returns the parent node (read-only)
17Parsed returns whether this node and its child nodes have been parsed (read-only)
18Prefix return namespace prefix (read-only)
19PRESERVEWHITESPACE Specifies whether to preserve white space (readable and writable)
20previousSibling returns the previous sibling node of this node (read-only)
21Text returns the text content of this node and its descendants (readable and writable)
22url returns the URL of the most recently loaded XML document (read-only)
23XML returns the XML representation of the node and its descendants (read-only)

Method:

1appendChild adds a new child node to the current node, placed after the last child node
2cloneNode returns a copy of the current node
3createAttribute Creating a new property
4createCDATASection Creating a CDATA segment that includes a given data
5createComment Creating a Comment node
6createDocumentFragment Creating DocumentFragment objects
7createElement Creating an Element node
8createEntityReference Creating EntityReference Objects
9createNode Create a node of the given type, name and namespace
10createPorcessingInstruction Creating an action instruction node
11createTextNode Creating a text node that includes the given data
12getElementsByTagName returns the collection of elements for the specified name
13hasChildNodes returns whether the current node has child nodes
14insertBefore inserting a child node before the specified node
15Load importing an XML document at the specified location
16loadXML importing an XML document of the specified string
17removeChild removes the specified child node from the child nodes list
18replaceChild replaces the specified child node from the list of child nodes
19Save Save the XML file to the specified node
20selectNodes matches the node in the specified match and returns a list of matching nodes
21selectSingleNode matches the node in the specified match and returns the first matching node
22transformNode converts a node and its descendants using the specified style sheet
23transformNodeToObject Convert a node and its descendants to an object using the specified style sheet


*********************************


DOM (Document Object model)
The introduction of the DOM (Document Object model) concept, this API makes HTML more powerful, but some of the DHTML friends are still somewhat sleepy, just because the current manual writing is not very scientific, is by the letter

To be divided, inconvenient to consult. In fact, the most important thing in DOM is to master the relationship between nodes and nodes (between node Andnode), want to learn the DOM in DHTML do not look through the

There are properties and methods, you have the Three Kingdoms when the Zhang Song of the "photographic" ability? No, listen to my analysis:

What Dom teaches us is a hierarchy, which you can understand as a tree structure, like our directory, a root directory, a subdirectory under the root directory, and a sub-directory with sub-directories.

Directory......

Root node:


The DOM calls each object in the hierarchy a node, as an example of HTML Hypertext Markup Language: a root of the entire document is &LT;HTML&GT, which can be used in the DOM

Document.documentelement to access it, it is the root node of the entire node tree (root)

Child nodes:

In the general sense, the node below the root node is the main document area <body>, to access the body tag, in the script should write:
Document.body
All text and HTML tags within the body area are nodes of the document, called text nodes, element nodes (or tag nodes), and you know that HTML is just text,

No matter how the page must be composed of these two nodes, can only be composed of these two nodes

The relationship between nodes:

The relationship between nodes is also the most important one in the DOM, how to correctly refer to the node object, it is necessary to understand the node tree nodes of the mutual description of the way, in DHTML,

JavaScript scripts use a whole set of methods and properties of each node object to describe additional node objects.


Absolute references to nodes:
Returns the root node of the document
Document.documentelement
Returns the tag node that is being clicked in the current document
Document.activeelement
Returns the source node that the mouse moved out of
Event.fromelement
Returns the source node in which the mouse is moved
Event.toelement
Returns the source node of the activation event
Event.srcelement

Relative references to nodes: (Sets the current node to nodes)
Returns the parent node
Node.parentnode
Node.parentelement
Returns a collection of child nodes (containing text nodes and label nodes)
Node.childnodes
Returns a child label node collection
Node.children
Returns a collection of child text nodes
Node.textnodes
Returns the first child node
Node.firstchild
Returns the last child node
Node.lastchild
Returns the next node of the same genus
Node.nextsibling
Returns the same genus as the previous node
Node.previoussibling

The various operations of the node: (Set the current node to nodes)

New label node handle:
Document.createelement (SNode)//parameter is the node tag name to be added, example: Newnode=document.createelement ("div");

1. Add a node:
Append child nodes:
Node.appendchild (Onode)//onode A new node handle for a living, for example: Node.appendchild (NewNode)
Apply Tag Node
Node.applyelment (Onode,swhere)//onode A new node handle, Swhere has two values: Outside/inside, added outside the current node or inside
Inserting nodes
Inode.insertbefore ()
Node.insertadjacentelement ()
Node.replaceadjacenttext ()

2, modify the node:

Delete a node
Node.remove ()
Node.removechild ()
Node.removenode ()

Replace node
Node.replacechild ()
Node.replacenode ()
Node.swapnode ()


2. Replication node:
Returns the replication Replication node reference
Node.clonenode (Ball)//ball is a Boolean value, true/false whether to clone all child nodes of the node

3. Node information
Whether to include a node
Node.contains ()
Whether there are child nodes
Node.haschildnodes ()

*******************************************************

The following is a JavaScript operation XML
<script language= "JavaScript" >
<!--
var doc = new ActiveXObject ("Msxml2.domdocument"); Ie5.5+,createobject ("Microsoft.XMLDOM")


Loading documents
Doc.load ("B.xml");

Create a file header
var p = doc.createprocessinginstruction ("xml", "version= ' 1.0 ' encoding= ' gb2312 '");

Add a file header
Doc.appendchild (P);

Get root contact for direct load
var root = doc.documentelement;

Create root contacts in two ways
var root = doc.createelement ("Students");
var root = Doc.createnode (1, "Students", "");

Create a sub-contact
var n = doc.createnode (1, "Ttyp", "");

Specify Child Contact text
N.text = "This is a test";

Create a grandchild Contact
var o = doc.createelement ("Sex");
O.text = "male"; Specify its text

Creating properties
var r = doc.createattribute ("id");
r.value= "Test";

Add Property
N.setattributenode (R);

Create a second property
var r1 = Doc.createattribute ("class");
R1.value= "TT";

Add Property
N.setattributenode (R1);

Delete Second Property
N.removeattribute ("class");

Add Sun Contacts
N.appendchild (o);

Add a text contact
N.appendchild (Doc.createtextnode ("This is a text node."));

Add Comment
N.appendchild (Doc.createcomment ("This is a comment\n");

Add a child contact
Root.appendchild (n);

Copy Contacts
var m = N.clonenode (true);

Root.appendchild (m);

Delete Contact
Root.removechild (root.childnodes (0));

Create a data segment
var c = doc.createcdatasection ("This is a CDATA");
C.text = "Hi,cdata";
Adding data segments
Root.appendchild (c);

Add Root Contact
Doc.appendchild (root);

Find Contacts
var a = Doc.getelementsbytagname ("Ttyp");
var a = Doc.selectnodes ("//ttyp");

Display the properties of the changed contacts
for (var i= 0;i<a.length;i++)
{
alert (a[i].xml);
for (Var j=0;j<a[i].attributes.length;j++)
{
alert (a[i].attributes[j].name);
}
}

modifying nodes, using XPath to locate nodes
var B = Doc.selectsinglenode ("//ttyp/sex");
B.text = "female";

alert (doc.xml);

XML save (required on the server side, client with FSO)
Doc.save ();

View Root junction XML
if (n)
{
alert (n.ownerdocument.xml);
}

-
</script>

Common methods for manipulating DOM node elements using JavaScript (Create/delete/replace/copy, etc.)

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.