search
HomeWeb Front-endJS TutorialSummary of common JavaScript native DOM operation APIs
Summary of common JavaScript native DOM operation APIsFeb 21, 2017 am 11:51 AM
DOM operationjavascript



I got stuck on this question during my recent interview, so I took the time to review it carefully.

Several kinds of objects

Node

Node is an interface, called node in Chinese, and many types of DOM elements are Inherited from it, all share the same basic properties and methods. Common Nodes include element, text, attribute, comment, document, etc. (so pay attention to the difference between node and element, element is a type of node).

Node has an attribute nodeType that represents the type of Node. It is an integer, and its values ​​represent the corresponding Node types. The details are as follows:

{
    ELEMENT_NODE: 1, // 元素节点
    ATTRIBUTE_NODE: 2, // 属性节点
    TEXT_NODE: 3, // 文本节点
    DATA_SECTION_NODE: 4,
    ENTITY_REFERENCE_NODE: 5,
    ENTITY_NODE: 6,
    PROCESSING_INSTRUCTION_NODE: 7,
    COMMENT_NODE: 8, // 注释节点
    DOCUMENT_NODE: 9, // 文档
    DOCUMENT_TYPE_NODE: 10,
    DOCUMENT_FRAGMENT_NODE: 11, // 文档碎片
    NOTATION_NODE: 12,
    DOCUMENT_POSITION_DISCONNECTED: 1,
    DOCUMENT_POSITION_PRECEDING: 2,
    DOCUMENT_POSITION_FOLLOWING: 4,
    DOCUMENT_POSITION_CONTAINS: 8,
    DOCUMENT_POSITION_CONTAINED_BY: 16,
    DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: 32
}

NodeList

The NodeList object is a collection of nodes, generally returned by Node.childNodes, document.getElementsByName and document.querySelectorAll.

However, it should be noted that the results of NodeList returned by Node.childNodes and document.getElementsByName are real-time (similar to HTMLCollection at this time), while the results returned by document.querySelectorAll are fixed, which is quite special.

For example:

var childNodes = document.body.childNodes;
console.log(childNodes.length); // 如果假设结果是“2”
document.body.appendChild(document.createElement('p'));
console.log(childNodes.length); // 此时的输出是“3”

HTMLCollection

HTMLCollection is a special NodeList, indicating that it contains several elements (the order of the elements is the order in the document flow ) is a general collection that is updated in real time and automatically updates when the elements it contains change. In addition, it is a pseudo array. If you want to operate them like an array, you need to call it like Array.prototype.slice.call(nodeList, 2).

Node search API

  • document.getElementById: Find elements based on ID, case sensitive, if there are multiple results, only the first one will be returned Each;

  • document.getElementsByClassName: Find elements based on class names. Multiple class names are separated by spaces and an HTMLCollection is returned. Note that compatibility is IE9+ (inclusive). In addition, not only document, other elements also support the getElementsByClassName method;

  • ##document.getElementsByTagName: Find elements based on tags, * means query all tags and return an HTMLCollection.

  • document.getElementsByName: Search based on the name attribute of the element and return a NodeList.

  • document.querySelector: Returns a single Node, IE8+ (inclusive), if multiple results are matched, only the first one is returned.

  • document.querySelectorAll: Returns a NodeList, IE8+ (inclusive).

  • document.forms: Get all the forms on the current page and return an HTMLCollection;

##Node creation API

The node creation API mainly includes four methods: createElement, createTextNode, cloneNode and createDocumentFragment.

createElement

Create element:

var elem = document.createElement("p");
elem.id = 'test';
elem.style = 'color: red';
elem.innerHTML = '我是新创建的节点';
document.body.appendChild(elem);

The element created through createElement does not belong to the document object, it is just created and not added to the html document, you need to call methods such as appendChild or insertBefore to add it to the HTML document.

createTextNode

Create a text node:

var node = document.createTextNode("我是文本节点");
document.body.appendChild(node);

cloneNode

Clone a node: node.cloneNode (true/false), which receives a bool parameter to indicate whether to copy child elements.

var from = document.getElementById("test");
var clone = from.cloneNode(true);
clone.id = "test2";
document.body.appendChild(clone);

Cloning a node will not clone the event, unless the event is bound using

using addEventListener and node.onclick= Anything bound using xxx; will not be copied.

createDocumentFragment

This method is used to create a DocumentFragment, which is a document fragment. It represents a lightweight document and is mainly used to store temporary nodes. Using it can greatly improve performance when manipulating DOM in large quantities.

Suppose there is a question that requires adding 10,000 li to ul. We first use the simplest method of splicing strings to achieve it:

<ul id="ul"></ul>
<script>
(function()
{
    var start = Date.now();
    var str = &#39;&#39;;
    for(var i=0; i<10000; i++) 
    {
        str += &#39;<li>第&#39;+i+&#39;个子节点</li>&#39;;
    }
    document.getElementById(&#39;ul&#39;).innerHTML = str;
    console.log(&#39;耗时:&#39;+(Date.now()-start)+&#39;毫秒&#39;); // 44毫秒
})();
</script>

Then change to the append method one by one. Needless to say, This method is definitely inefficient:

<ul id="ul"></ul>
<script>
(function()
{
    var start = Date.now();
    var str = &#39;&#39;, li;
    var ul = document.getElementById(&#39;ul&#39;);
    for(var i=0; i<10000; i++)
    {
        li = document.createElement(&#39;li&#39;);
        li.textContent = &#39;第&#39;+i+&#39;个子节点&#39;;
        ul.appendChild(li);
    }
    console.log(&#39;耗时:&#39;+(Date.now()-start)+&#39;毫秒&#39;); // 82毫秒
})();
</script>

Finally, try the document fragmentation method. It is foreseeable that this method is definitely much better than the second method, but it should not be as fast as the first one:

<ul id="ul"></ul>
<script>
(function()
{
    var start = Date.now();
    var str = &#39;&#39;, li;
    var ul = document.getElementById(&#39;ul&#39;);
    var fragment = document.createDocumentFragment();
    for(var i=0; i<10000; i++)
    {
        li = document.createElement(&#39;li&#39;);
        li.textContent = &#39;第&#39;+i+&#39;个子节点&#39;;
        fragment.appendChild(li);
    }
    ul.appendChild(fragment);
    console.log(&#39;耗时:&#39;+(Date.now()-start)+&#39;毫秒&#39;); // 63毫秒
})();
</script>

Node modification API

Node modification API has the following characteristics:

    Whether it is adding or replacing nodes, If it was originally on the page, the node at its original location will be removed;
  1. Events bound to the node itself will not disappear after modification;
appendChild

This has actually been used many times before. The syntax is:

parent.appendChild(child);

It will append the child to the end of the parent's child node. In addition, if the added node is a node that exists in a page, the node will be added to a new location after execution, and the node will be removed from its original location, which means that there will not be two nodes at the same time. on the page and its events remain.

insertBefore

Insert a node in front of another node, syntax:

parentNode.insertBefore(newNode, refNode);

这个API个人觉得设置的非常不合理,因为插入节点只需要知道newNode和refNode就可以了,parentNode是多余的,所以jQuery封装的API就比较好:

newNode.insertBefore(refNode); // 如 $("p").insertBefore("#foo");

所以切记不要把这个原生API和jQuery的API使用方法搞混了!为了加深理解,这里写一个简单的例子:

<p id="parent">
    我是父节点
    <p id="child">
        我是旧的子节点
    </p>
</p>
<input type="button" id="insertNode" value="插入节点" />
<script>
var parent = document.getElementById("parent");
var child = document.getElementById("child");
document.getElementById("insertNode").addEventListener(&#39;click&#39;, function()
{
    var newNode = document.createElement("p");
    newNode.textContent = "我是新节点";
    parent.insertBefore(newNode, child);
}, false);
</script>

关于第二个参数:

  • refNode是必传的,如果不传该参数会报错;

  • 如果refNode是undefined或null,则insertBefore会将节点添加到末尾;

removeChild

removeChild用于删除指定的子节点并返回子节点,语法:

var deletedChild = parent.removeChild(node);

deletedChild指向被删除节点的引用,它仍然存在于内存中,可以对其进行下一步操作。另外,如果被删除的节点不是其子节点,则将会报错。一般删除节点都是这么删的:

function removeNode(node)
{
    if(!node) return;
    if(node.parentNode) node.parentNode.removeChild(node);
}

replaceChild

replaceChild用于将一个节点替换另一个节点,语法:

parent.replaceChild(newChild, oldChild);

节点关系API

DOM中的节点相互之间存在着各种各样的关系,如父子关系,兄弟关系等。

父关系API

  • parentNode :每个节点都有一个parentNode属性,它表示元素的父节点。Element的父节点可能是Element,Document或DocumentFragment;

  • parentElement :返回元素的父元素节点,与parentNode的区别在于,其父节点必须是一个Element元素,如果不是,则返回null;

子关系API

  • children :返回一个实时的 HTMLCollection ,子节点都是Element,IE9以下浏览器不支持;

  • childNodes :返回一个实时的 NodeList ,表示元素的子节点列表,注意子节点可能包含文本节点、注释节点等;

  • firstChild :返回第一个子节点,不存在返回null,与之相对应的还有一个 firstElementChild ;

  • lastChild :返回最后一个子节点,不存在返回null,与之相对应的还有一个 lastElementChild ;

兄弟关系型API

  • previousSibling :节点的前一个节点,如果不存在则返回null。注意有可能拿到的节点是文本节点或注释节点,与预期的不符,要进行处理一下。

  • nextSibling :节点的后一个节点,如果不存在则返回null。注意有可能拿到的节点是文本节点,与预期的不符,要进行处理一下。

  • previousElementSibling :返回前一个元素节点,前一个节点必须是Element,注意IE9以下浏览器不支持。

  • nextElementSibling :返回后一个元素节点,后一个节点必须是Element,注意IE9以下浏览器不支持。

元素属性型API

setAttribute

给元素设置属性:

element.setAttribute(name, value);

其中name是特性名,value是特性值。如果元素不包含该特性,则会创建该特性并赋值。

getAttribute

getAttribute返回指定的特性名相应的特性值,如果不存在,则返回null:

var value = element.getAttribute("id");

样式相关API

直接修改元素的样式

elem.style.color = &#39;red&#39;;
elem.style.setProperty(&#39;font-size&#39;, &#39;16px&#39;);
elem.style.removeProperty(&#39;color&#39;);

动态添加样式规则

var style = document.createElement(&#39;style&#39;);
style.innerHTML = &#39;body{color:red} #top:hover{background-color: red;color: white;}&#39;;
document.head.appendChild(style);

window.getComputedStyle

通过 element.sytle.xxx 只能获取到内联样式,借助 window.getComputedStyle 可以获取应用到元素上的所有样式,IE8或更低版本不支持此方法。

var style = window.getComputedStyle(element[, pseudoElt]);

getBoundingClientRect

getBoundingClientRect 用来返回元素的大小以及相对于浏览器可视窗口的位置,用法如下:

var clientRect = element.getBoundingClientRect();

clientRect是一个 DOMRect 对象,包含width、height、left、top、right、bottom,它是相对于窗口顶部而不是文档顶部,滚动页面时它们的值是会发生变化的。

Summary of common JavaScript native DOM operation APIs

 

以上就是JavaScript常见原生DOM操作API总结的内容,更多相关内容请关注PHP中文网(www.php.cn)!

 

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()方法添加的事件处理程序。

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

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

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

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

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)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools