Basic tutorial on JavaScript operations on html dom nodes, javascriptdom

Source: Internet
Author: User

Basic tutorial on JavaScript operations on html dom nodes, javascriptdom

Because DOM exists, we can use JavaScript to obtain, create, modify, or delete nodes.
NOTE: The elements in the example below are all element nodes.
Get Node

Parent-child relationship

element.parentNodeelement.firstChild/element.lastChildelement.childNodes/element.children

Sibling relationship

element.previousSibling/element.nextSiblingelement.previousElementSibling/element.nextElementSibling

Obtaining nodes through the direct relationship between nodes greatly reduces code Maintainability (the changes in the relationship between nodes directly affect the nodes to be obtained), and the interface can effectively solve this problem.

Obtaining nodes through the direct relationship between nodes greatly reduces code Maintainability (the changes in the relationship between nodes directly affect the nodes to be obtained), and the interface can effectively solve this problem.

<!DOCTYPE html>

NTOE: careful people will find that in the node traversal example, there is no space between the body, ul, li, and p nodes, because if there is space, then space is treated as a TEXT node, and ulNode is used. previussibling gets an empty text node instead of the <li> First </li> node. That is, the attributes of node traversal get all node types, while element traversal only gets the corresponding element nodes. Generally, the traversal attribute of an element node is used.
Implement element. children for browser compatibility
Some earlier browsers do not support the element. children method, but we can use the following method for compatibility.

NOTE: This compatibility method is the first draft and has not been tested.
Interface to get element nodes

getElementByIdgetElementsByTagNamegetElementsByClassNamequerySelectorquerySelectorAll

GetElementById

Obtains the Node object of the specified id in the document.

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

Dynamically obtain a set of nodes with the specified Tag Element (the returned value is affected by DOM changes and its value changes ). This interface can be obtained directly through the element without directly acting on the document.

// Example var collection = element. getElementsByTagName ('tagname'); // obtain all the nodes of the specified Element var allNodes = document. getElementsByTagName ('*'); // obtain the node var elements = document for all p elements. getElementsByTagName ('P'); // retrieve the first p element var p = elements [0];


GetElementsByClassName
Obtains all nodes with the specified class in the specified element. The selection of multiple classes can be separated by spaces, which is irrelevant to the sequence.
Var elements = element. getElementsByClassName ('classname ');
NOTE: IE9 and earlier versions do not support getElementsByClassName
Compatibility Method

Function getElementsByClassName (root, className) {// Feature Detection if (root. getElementsByClassName) {// give priority to the W3C standard interface return root. getElementsByClassName (className);} else {// obtain 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 the class for (var I = 0, element; element = elements [I]; I ++) {classNameStr = ''+ element. getAttribute ('class') + ''; flag = true; for (var j = 0, name; name = className [j]; j ++) {if (classNameStr. indexOf (''+ name +'') =-1) {flag = false; break;} if (flag) {result. push (element) ;}} return result ;}}

QuerySelector/querySelectorAll

Obtain a list (the returned results will not be affected by subsequent DOM modifications and will not change after obtaining) that matches the first or all elements of the passed CSS selector.

var listElementNode = element.querySelector('selector');var listElementsNodes = element.querySelectorAll('selector');var sampleSingleNode = element.querySelector('#className');var sampleAllNodes = element.querySelectorAll('#className');

NOTE: IE9 does not support querySelector and querySelectorAll.
Create a node

Create a node> Set Properties> insert a node

var element = document.createElement('tagName');

Modify a node

TextContent
Obtain or set the text content of the node and its child nodes (for all text content in the node ).

Element. textContent; // get element. textContent = 'new content ';

NOTE: IE 9 and earlier versions are not supported.
InnerText (not compliant with W3C specifications)
Obtains or sets the text content of the node and its descendants. The effect on textContent is almost the same.

element.innerText;

NOTE: does not comply with W3C specifications and does not support FireFox browsers.
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

Append an element node to the specified element.

var aChild = element.appendChild(aChild);

InsertBefore

Insert 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 a specified node.

var child = element.removeChild(child);

InnerHTML

Obtains or sets all HTML content of a specified node. Replace all the previous content and create a new batch of nodes (remove previously added events and styles ). InnerHTML does not check the content. It runs directly and replaces the original content.
NOTE: It is only recommended to create a new node. It cannot be used under user control.

var elementsHTML = element.innerHTML;

Existing Problems +

  • Memory leakage in earlier versions of IE
  • Security Question (you can run the script code in the name)

PS: appendChild (), insertBefore ()
Insert a node using appendChild () and insertBefore () will be returned to the inserted node,

// Because both methods operate on the child nodes of a node, the parent node must be obtained now. someNode in the Code indicates the parent node // use appendChild () method To insert a node var returnedNode = someNode. appendChild (newNode); alert (returnedNode = newNode) // true // use the insertBefore () method to insert the node var returnedNode = someNode. appendChild (newNode); alert (returnedNode = newNode) // true

It is worth noting that if the node inserted by the two methods already exists in the Document Tree, the node will be moved to a new location instead of being copied.

<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 page output result is the same as that without Javascript, And the element is not copied. Because the element is in the last position, it is the same as no operation. If you change the positions of the two child element vertices of the element with id test, you can see in firbug that the two divs have been replaced.
If we want to copy an element with id a and add it to the document, the copied element must be removed from the document stream. In this way, the added and copied nodes will not affect the original nodes in the document flow after they are 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 below to implement deep replication of nodes. nodes copied using this method will be out of the Document Stream. Of course, I do not recommend using this method to copy elements with the id attribute. Because the id value in the document is unique.

<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 this section. replaceNode (newNode, node) replaces the node and returns this node. These two methods are relatively easier to use.

Articles you may be interested in:
  • Access, create, modify, and delete DOM nodes in JavaScript
  • Example of how javascript adds a DOM node to a document
  • Javascript method for getting the next node of dom
  • Example of adding a JavaScript DOM Node
  • Javascript obtains html dom parent, child, and adjacent nodes
  • Operations on dom nodes by js and jquery (Create/append)
  • Implementation Code for building the DOM node Structure of a page using JS
  • Use DOM in js to copy (clone) the node name data to the new XML file.
  • How to clone cloneNode text nodes using javascript dom operations
  • Summary of Js methods for getting html dom node Elements
  • Javascript beginners Chapter 8 js dom node attributes
  • JavaScript node operations and DOMDocument attributes and Methods

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.