Home > Web Front-end > JS Tutorial > body text

Basic tutorial on operating HTML DOM nodes with JavaScript_Basic knowledge

WBOY
Release: 2016-05-16 15:11:03
Original
1639 people have browsed it

Because of the existence of DOM, this allows us to obtain, create, modify, or delete nodes through JavaScript.
NOTE: The elements in the examples provided below are all element nodes.
Get node

Father-son relationship

element.parentNode
element.firstChild/element.lastChild
element.childNodes/element.children
Copy after login

Brotherly relationship

element.previousSibling/element.nextSibling
element.previousElementSibling/element.nextElementSibling
Copy after login

Acquiring nodes through the direct relationship between nodes will greatly reduce the maintainability of the code (changes in the relationship between nodes will directly affect the acquisition of nodes), but this problem can be effectively solved through interfaces.

Acquiring nodes through the direct relationship between nodes will greatly reduce the maintainability of the code (changes in the relationship between nodes will directly affect the acquisition of nodes), but this problem can be effectively solved through interfaces.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>ELEMENT_NODE & TEXT_NODE</title>
</head>
<body>
 <ul id="ul">
 <li>First</li>
 <li>Second</li>
 <li>Third</li>
 <li>Fourth</li>
 </ul>
 <p>Hello</p>
 <script type="text/javascript">
 var ulNode = document.getElementsByTagName("ul")[0];
 console.log(ulNode.parentNode);    //<body></body>
 console.log(ulNode.previousElementSibling); //null
 console.log(ulNode.nextElementSibling);  //<p>Hello</p>
 console.log(ulNode.firstElementChild);  //<li>First</li>
 console.log(ulNode.lastElementChild);  //<li>Fourth</li>
 </script>
</body>
</html>
Copy after login

NTOE: Careful people will find that in the example of node traversal, there are no spaces between the body, ul, li, and p nodes, because if there are spaces, then the spaces will be regarded as a TEXT node, so use ulNode.previousSibling gets an empty text node instead of the

  • First
  • node. That is, several attributes of node traversal will get all node types, while element traversal will only get the corresponding element nodes. Under normal circumstances, the traversal attribute of element nodes is more commonly used.
    Implement browser-compatible version of element.children
    Some older browsers do not support the element.children method, but we can use the following method to achieve compatibility.

    <html lang>
    <head>
     <meta charest="utf-8">
     <title>Compatible Children Method</title>
    </head>
    <body id="body">
     <div id="item">
     <div>123</div>
     <p>ppp</p>
     <h1>h1</h1>
     </div>
     <script type="text/javascript">
     function getElementChildren(e){
      if(e.children){
      return e.children;
      }else{
      /* compatible other browse */
      var i, len, children = [];
      var child = element.firstChild;
      if(child != element.lastChild){
       while(child != null){
       if(child.nodeType == 1){
        children.push(child);
       }
       child = child.nextSibling;
       }
      }else{
       children.push(child);
      }
      return children;
      }
     }
     /* Test method getElementChildren(e) */
     var item = document.getElementById("item");
     var children = getElementChildren(item);
     for(var i =0; i < children.length; i++){
      alert(children[i]);
     }
     </script>
    </body>
    </html>
    
    
    Copy after login

    NOTE: This compatibility method is a preliminary draft and has not been tested for compatibility.
    Interface to get element node

    getElementById
    getElementsByTagName
    getElementsByClassName
    querySelector
    querySelectorAll
    
    Copy after login

    2016311163518624.png (793×256)

    getElementById

    Get the node object with the specified id in the document.

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

    Dynamicly obtain a collection of element nodes with specified tags (its return value will be affected by DOM changes, and its value will change). This interface can be obtained directly through the element and does not have to act directly on the document.

    // 示例
    var collection = element.getElementsByTagName('tagName');
    
    // 获取指定元素的所有节点
    var allNodes = document.getElementsByTagName('*');
    
    // 获取所有 p 元素的节点
    var elements = document.getElementsByTagName('p');
    // 取出第一个 p 元素
    var p = elements[0];
    
    
    Copy after login


    getElementsByClassName
    Get all nodes with the specified class in the specified element. Multiple class options can be separated by spaces, regardless of order.
    var elements = element.getElementsByClassName('className');
    NOTE: IE9 and below do not support getElementsByClassName
    Compatible methods

    function getElementsByClassName(root, className) {
     // 特性侦测
     if (root.getElementsByClassName) {
     // 优先使用 W3C 规范接口
     return root.getElementsByClassName(className);
     } else {
     // 获取所有后代节点
     var elements = root.getElementsByTagName('*');
     var result = [];
     var element = null;
     var classNameStr = null;
     var flag = null;
    
     className = className.split(' ');
    
     // 选择包含 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;
     }
    }
    
    
    Copy after login

    querySelector / querySelectorAll

    Get the first element or all elements of a list (the return result will not be affected by subsequent DOM modifications and will not change after acquisition) that matches the incoming CSS selector.

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

    NOTE: IE9 does not support querySelector and querySelectorAll
    Create Node

    Create node -> Set properties -> Insert node

    var element = document.createElement('tagName');
    
    Copy after login

    Modify node

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

    element.textContent; // 获取
    element.textContent = 'New Content';
    
    Copy after login

    NOTE: IE 9 and below are not supported.
    innerText (not W3C compliant)
    Gets or sets the text content of the node and its descendants. Its effect on textContent is almost the same.

    element.innerText;
    
    Copy after login

    NOTE: Not compliant with W3C specifications and does not support FireFox browser.
    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;
     });
    }
    
    Copy after login

    Insert node

    appendChild

    Append an element node within the specified element.

    var aChild = element.appendChild(aChild);
    
    Copy after login

    insertBefore

    Insert the specified element before the specified node of the specified element.

    var aChild = element.insertBefore(aChild, referenceChild);
    
    Copy after login

    Delete node

    Delete the child element nodes of the specified node.

    var child = element.removeChild(child);
    
    Copy after login

    innerHTML

    Get or set all HTML content in the specified node. Replaces all previous internal content and creates a completely new batch of nodes (removing previously added events and styles). innerHTML does not check the content, runs directly and replaces the original content.
    NOTE: This is only recommended when creating a brand new node. Not to be used under user control.

    var elementsHTML = element.innerHTML;
    
    Copy after login

    存在的问题+

    • 低版本 IE 存在内存泄露
    • 安全问题(用户可以在名称中运行脚本代码)

    PS: appendChild() , insertBefore()插入节点需注意的问题
    使用appendChild()和insertBefore()插入节点都会返回给插入的节点,

    //由于这两种方法操作的都是某个节点的子节点,所以必须现取得父节点,代码中 someNode 表示父节点 
    //使用appendChild()方法插入节点 
    var returnedNode = someNode.appendChild(newNode); 
    alert(returnedNode == newNode) //true 
     
    //使用insertBefore()方法插入节点 
    var returnedNode = someNode.appendChild(newNode); 
    alert(returnedNode == newNode) //true 
    
    
    Copy after login

    值得注意的是,如果这两种方法插入的节点原本已经存在与文档树中,那么该节点将会被移动到新的位置,而不是被复制。

    <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> 
    
    Copy after login

    在这段代码中,页面输出的结果和没有Javascript时是一样的,元素并没有被复制,由于元素本来就在最后一个位置,所以就和没有操作一样。如果把id为test的元素的两个子元素点换位置,就可以在firbug中看到这两个div已经被调换了位置。
    如果我们希望把id为a的元素复制一个,然后添加到文档中,那么必须使被复制的元素现脱离文档流。这样被添加复制的节点被添加到文档中之后就不会影响到文档流中原本的节点。即我们可以把复制的元素放到文档的任何地方,而不影响被复制的元素。下面使用了cloneNode()方法,实现节点的深度复制,使用这种方法复制的节点会脱离文档流。当然,我不建议使用这种方法复制具有id属性的元素。因为在文档中id值是唯一的。

    <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> 
    
    
    Copy after login

    相似的操作方法还有 removeNode(node)删除一个节点,并返回该节;replaceNode(newNode,node)替换node节点,并返回该节点。这两种方法相对来说更容易使用一些。

    Related labels:
    source:php.cn
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template