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

JavaScript knowledge points collection: obtaining elements and nodes

WBOY
Release: 2022-05-16 17:58:57
forward
2400 people have browsed it

This article brings you relevant knowledge about javascript, which mainly introduces the relevant content about obtaining elements and nodes, including obtaining elements through id, class name, name, and tag name. , creating, deleting, cloning nodes and other issues, let’s take a look at them together, I hope it will be helpful to everyone.

JavaScript knowledge points collection: obtaining elements and nodes

[Related recommendations: javascript video tutorial, web front-end

Get elements

  • Get by ID (getElementById)
  • By name attribute (getElementsByName)
  • By tag name (getElementsByTagName)
  • By class name (getElementsByClassName)
  • Get an element by selector (querySelector)
  • By selection The device gets a set of elements (querySelectorAll)
  • Method to get html (document.documentElement)
  • Method to get body (document .body)

1. Get by ID (getElementById)

// 1 获取元素节点
    // 通过id的方式( 通过id查找元素,大小写敏感,如果有多个id只找到第一个)
    document.getElementById('p1');
Copy after login

  • The context must be document.
  • Must pass parameters. The parameter is of string type and is used to obtain the id of the element.
  • The return value only obtains one element, and returns null if it is not found.

2. By class name (getElementsByClassName)

    // 通过类名查找元素,多个类名用空格分隔,得到一个HTMLCollection(一个元素集合,有length属性,可以通过索引号访问里面的某一个元素)
    var cls = document.getElementsByClassName('a b');
    console.log(cls);
Copy after login
  • The parameter is the class name of the element.
  • The return value is a class array, if not found an empty array is returned

3. Through the name attribute (getElementsByName)

 // 通过name属性查找,返回一个NodeList(一个节点集合,有length属性,可以通过索引号访问)
   var nm =  document.getElementsByName('c');
    console.log(nm);
Copy after login

4. By tag name (getElementsByTagName)

    // 通过标签名查找元素 返回一个HTMLCollection
    document.getElementsByTagName('p');
Copy after login
  • The parameter is to get the tag name attribute of the element, which is not case-sensitive.
  • The return value is an array-like array, if not found an empty array is returned

5. Get an element through the selector (querySelector)

document.querySelector('.animated')
Copy after login
Copy after login
  • The parameter is the selector, such as: "p .className".
  • Return a single node, if there are multiple matching elements, return the first one

6. Get a set of elements through the selector (querySelectorAll)

document.querySelector('.animated')
Copy after login
Copy after login
  • The return value is a class array

Get the node

In the Document Object Model (DOM), each node is an object. DOM nodes have three important attributes

1. nodeName: the name of the node

2. nodeValue: the name of the node Value

3. nodeType: The type of node

1. nodeName attribute: The name of the node, It is read-only.

  • The nodeName of the element node is the same as the label name
  • The nodeName of the attribute node is the name of the attribute
  • The nodeName of the text node is always #text
  • The nodeName of the document node is always #document

2. nodeValue attribute: the value of the node

  • The nodeValue of the element node is undefined Or null
  • The nodeValue of the text node is the text itself
  • The nodeValue of the attribute node is the value of the attribute

3. nodeType attribute: the type of node, It is read-only. The following commonly used node types:

  • Element type Node type
  • Element 1
  • Attribute 2
  • Text 3 Space Also returns 3
  • Comment 8
  • Document 9

Create node:

1. Create node: createElement('')

 // 创建元素,只是创建出来并未添加到html中,需要与appendChild 配合使用
    var elem = document.createElement('p');
    elem.id = 'test';
    elem.style = 'color: red';
    elem.innerHTML = '我是新创建的节点';
    document.body.appendChild(elem);
Copy after login

2. Insert node: appendChild ()

  • Usage is: parent. appendChild(child)
  • will add the child node to the end of the parent
  • If the child node already exists, the original node will be removed and the new node will be added to Finally, but the event will remain
 var oNewp=document.createElement("p");
      var oText=document.createTextNode("World Hello");
      oNewp.appendChild(oText);
Copy after login

2-1. Insert node: insertBefore()

  • 用法是 parent.insertBefore(newNode,refNode);
     var oOldp=document.body.getElementsByTagName("p")[0];
      document.body.insertBefore(oNewp,oOldp);
Copy after login

  删除节点

1.删除节点:removeChild

  • 用法是:parent.removeChild(child) 
  • 如果删除的不是父元素的子节点会报错
   var op=document.body.getElementsByTagName("p")[0];
         op.parentNode.removeChild(op);
Copy after login

   克隆节点

1.克隆节点:parent.cloneNode() false 或者true

  • 克隆节点(需要接受一个参数来表示是否复制元素)
  // 克隆节点(需要接受一个参数来表示是否复制元素)
    var form =  document.getElementById('test');
    var clone = form.cloneNode(true);
    clone.id = 'test2';
    document.body.appendChild(clone);
Copy after login

   替换节点

1.替换节点 方法node.replace(new,old) 

       var oOldp=document.body.getElementsByTagName("p")[0];
       oOldp.parentNode.replaceChild(oNewp,oOldp);
Copy after login

  文档碎片框 

  • 作用:当向document中添加大量的节点时,如果逐个添加将会十分缓慢,这时可以使用文档碎片一次性添加到document中
  • 语法:document.createDocumentFragment();
  • 承载节点
 (function()
    {
        var start = Date.now();
        var str = '', li;
        var ul = document.getElementById('ul');
        var fragment = document.createDocumentFragment();
        for(var i=0; i<10000; i++)
        {
            li = document.createElement('li');
            li.textContent = '第'+i+'个子节点';
            fragment.appendChild(li);
        }
        ul.appendChild(fragment);
        console.log('耗时:'+(Date.now()-start)+'毫秒'); // 63毫秒
    })();
Copy after login

【相关推荐:javascript视频教程web前端

The above is the detailed content of JavaScript knowledge points collection: obtaining elements and nodes. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!