search
HomeWeb Front-endJS TutorialBasic tutorial on operating HTML DOM nodes with JavaScript_Basic knowledge

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

Brotherly relationship

element.previousSibling/element.nextSibling
element.previousElementSibling/element.nextElementSibling

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>

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 id="h">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>
    
    

    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
    

    2016311163518624.png (793×256)

    getElementById

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

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

    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];
    
    


    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;
     }
    }
    
    

    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');
    
    

    NOTE: IE9 does not support querySelector and querySelectorAll
    Create Node

    Create node -> Set properties -> Insert node

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

    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';
    

    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;
    

    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;
     });
    }
    

    Insert node

    appendChild

    Append an element node within 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 node

    Delete the child element nodes of the specified node.

    var child = element.removeChild(child);
    

    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;
    

    存在的问题+

    • 低版本 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 
    
    

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

    <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> 
    

    在这段代码中,页面输出的结果和没有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> 
    
    

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

    Statement
    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
    es6数组怎么去掉重复并且重新排序es6数组怎么去掉重复并且重新排序May 05, 2022 pm 07:08 PM

    去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

    JavaScript的Symbol类型、隐藏属性及全局注册表详解JavaScript的Symbol类型、隐藏属性及全局注册表详解Jun 02, 2022 am 11:50 AM

    本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

    原来利用纯CSS也能实现文字轮播与图片轮播!原来利用纯CSS也能实现文字轮播与图片轮播!Jun 10, 2022 pm 01:00 PM

    怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

    JavaScript对象的构造函数和new操作符(实例详解)JavaScript对象的构造函数和new操作符(实例详解)May 10, 2022 pm 06:16 PM

    本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

    JavaScript面向对象详细解析之属性描述符JavaScript面向对象详细解析之属性描述符May 27, 2022 pm 05:29 PM

    本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

    javascript怎么移除元素点击事件javascript怎么移除元素点击事件Apr 11, 2022 pm 04:51 PM

    方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

    foreach是es6里的吗foreach是es6里的吗May 05, 2022 pm 05:59 PM

    foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。

    整理总结JavaScript常见的BOM操作整理总结JavaScript常见的BOM操作Jun 01, 2022 am 11:43 AM

    本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Article

    R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
    3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Best Graphic Settings
    3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. How to Fix Audio if You Can't Hear Anyone
    3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    WWE 2K25: How To Unlock Everything In MyRise
    3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    mPDF

    mPDF

    mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

    MinGW - Minimalist GNU for Windows

    MinGW - Minimalist GNU for Windows

    This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

    SublimeText3 English version

    SublimeText3 English version

    Recommended: Win version, supports code prompts!

    DVWA

    DVWA

    Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

    VSCode Windows 64-bit Download

    VSCode Windows 64-bit Download

    A free and powerful IDE editor launched by Microsoft