Basic tutorial on JavaScript manipulating HTML DOM nodes _ basics

Source: Internet
Author: User
Tags tagname

Because of the DOM, this allows us to get, create, modify, or delete nodes through JavaScript.
Note: The elements in the example provided below are ELEMENT nodes.
Get node

Parent-child Relationship

Element.parentnode
element.firstchild/element.lastchild
Element.childnodes/element.children

Brother relationship

Element.previoussibling/element.nextsibling
element.previouselementsibling/element.nextelementsibling

Getting the node through the direct relationship of the node will cause the code maintainability to be greatly reduced (the relationship between the nodes will directly affect the acquisition node), and the interface can effectively solve the problem.

Getting the node through the direct relationship of the node will cause the code maintainability to be greatly reduced (the relationship between the nodes will directly affect the acquisition node), and the interface can effectively solve the problem.

 <! DOCTYPE html>  
 

Ntoe: Careful people will find that in the node traversal example, Body, UL, Li, p node is no space between, because if there are spaces, then the space will be as a text node, So the ulnode.previoussibling is acquired as an empty text node, not a <li>First</li> node. That is, several properties of the node traversal will get all the node types, and the element traversal will only get the corresponding element nodes. In general, the use of a more or less of the element node traversal property.
Implementing a browser-compatible version of Element.children
There are some versions of browsers that do not support the Element.children method, but we can implement it in the following ways.

  
 

Note: This compatibility method is the first draft and has not yet been tested for compatibility.
interface Gets the element node

getElementById
getelementsbytagname
getelementsbyclassname
queryselector
queryselectorall

getElementById

Gets the node object for the specified ID in the document.

var element = document.getElementById (' id ');
getElementsByTagName

Dynamically gets the collection with the specified label element node, whose return value is affected by the change in the DOM, and its value changes. This interface can be obtained directly from the element without directly acting on the document.

Example
var collection = Element.getelementsbytagname (' tagName ');

Gets all nodes of the specified element
var allnodes = document.getelementsbytagname (' * ');

Gets the node of all P elements
var elements = document.getelementsbytagname (' P ');
Take out the first P element
var p = elements[0];


getelementsbyclassname
gets all nodes in the specified element that have the specified class. Multiple class-selectable selections can be separated by spaces, regardless of order.
var elements = element.getelementsbyclassname (' ClassName ');
NOTE:IE9 and versions do not support Getelementsbyclassname
Compatibility method

function Getelementsbyclassname (root, ClassName) {
 //feature detection
 if (root.getelementsbyclassname) {
 ///Priority use of the Consortium Canonical interface return
 Root.getelementsbyclassname (className);
 } else {
 //Get all descendant nodes
 var elements = Root.getelementsbytagname (' * ');
 var result = [];
 var element = null;
 var classnamestr = null;
 var flag = null;

 ClassName = Classname.split (");

 Select the element containing class for
 (var i = 0, element; element = Elements[i]; i++) {
  classnamestr = ' + Element.getattribu Te (' class ') + ';
  Flag = true;
  for (var j = 0, name; name = Classname[j]; j +) {
  if (classnamestr.indexof (' + name + ') = = 1) {
   flag = FA LSE;
   break;
  }
  }
  if (flag) {
  Result.push (element);
  }
 }
 return result;
 }


Queryselector/queryselectorall

Gets a list (its return result will not be affected by subsequent DOM modifications and will not be changed) to match the first element or all elements of the incoming CSS selector.

var listelementnode = element.queryselector (' selector ');
var listelementsnodes = element.queryselectorall (' selector ');

var samplesinglenode = element.queryselector (' #className ');
var sampleallnodes = element.queryselectorall (' #className ');

NOTE:IE9 don't support Queryselector and Queryselectorall
Creating Nodes

Creating nodes-> setting properties-> inserting nodes

var element = document.createelement (' TagName ');

modifying nodes

Textcontent
Gets or sets the textual content of the node and its descendant nodes (for all textual content in the node).

Element.textcontent; Get
element.textcontent = ' New Content ';

Note: IE 9 and its version are not supported.
innertext (not conforming to the rules of the Consortium)
Gets or sets the text content of the node and the descendant of the node. The effect is almost consistent with textcontent.

Element.innertext;

Note: does not conform to the standard of the web, FireFox browser is not supported.
FireFox Compatibility Solution

if (! (' InnerText ' in Document.body)} {
 htmlelement.prototype.__definegetter__ (' innertext ', function () {
 return this.textcontent;
 });
 htmlelement.prototype.__definesetter__ (' innertext ', function (s) {return
 this.textcontent = s;
 });
}

Insert Node

AppendChild

Appends an element node to the specified element.

var achild = Element.appendchild (achild);

InsertBefore

Inserts the specified element before the specified node of the specified element.

var achild = Element.insertbefore (Achild, referencechild);

Delete a node

Deletes the child element node of the specified node.

var child = Element.removechild (child);

InnerHTML

Gets or sets all the HTML content in the specified node. Replaces all previous internal content and creates a new batch of nodes (removing previously added events and styles). InnerHTML does not check the content, runs directly and replaces the original content.
Note: It is only recommended to use when creating a completely new node. Can not be used in the case of user control.

var elementshtml = element.innerhtml;

Problems in existence +

    • Low version IE has a memory leak
    • Security issues (Users can run script code in the name)

Ps:appendchild (), insertbefore () Insert node to be aware of the problem
Inserting a node using the AppendChild () and InsertBefore () is returned to the inserted node.

Since both methods operate on the child nodes of a node, you must now obtain the parent node, in which the Somenode represents the parent node 
/////AppendChild () method to insert the node 
var returnednode = Somenode.appendchild (NewNode); 
Alert (Returnednode = = NewNode)//true 
 
//Use InsertBefore () method to insert node 
var returnednode = Somenode.appendchild ( NewNode); 
Alert (Returnednode = = NewNode)//true 

It is noteworthy that if both methods insert a node that already exists in the document tree, the node will be moved to a new location instead of being replicated.

<div id= "Test" > 
 <div>adscasdjk</div> 
  <div id= "a" >adscasdjk</div> 
</ div> 
<script type= "Text/javascript" > 
 var t = document.getElementById ("test"); 
 var a = document.getElementById (' a '); 
 var tt = A.clonenode (true); 
 T.appendchild (a); 
</script> 

In this code, the output of the page is the same as when there is no JavaScript, and the element is not replicated, because the element is in the last position, so it is not the same as no action. If you change the position of the two child elements of the element with the ID test, you can see in the firbug that the two div has been swapped.
If we want to copy an element with ID A and then add it to the document, you must leave the copied elements out of the document stream. The node that is added to the replication will not affect the original node in the document stream after it is added to the document. That is, we can place the copied elements anywhere in the document without affecting the copied elements. The CloneNode () method is used to implement deep replication of nodes, and nodes that are replicated using this method are detached from the document stream. Of course, I do not recommend using this method to copy elements that have an id attribute. Because the ID value is unique in the document.

<div id= "Test" > 
 <div>adscasdjk</div> 
  <div id= "a" >adscasdjk</div> 
</ div> 
<script type= "Text/javascript" > 
 var t = document.getElementById ("test"); 
 var a = document.getElementById (' a '); 
 var tt = A.clonenode (true); 
 T.appendchild (TT); 
</script> 

Similarly, removenode (node) deletes a node and returns the section, ReplaceNode (Newnode,node) replaces the node node and returns it. These two methods are relatively easier to use.

Related Article

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.