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

Summary of common JavaScript native DOM operation APIs

黄舟
Release: 2017-02-21 11:51:35
Original
1136 people have browsed it



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

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

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

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

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

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

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

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

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

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

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

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

所以切记不要把这个原生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>
Copy after login

关于第二个参数:

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

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

removeChild

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

var deletedChild = parent.removeChild(node);
Copy after login

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

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

replaceChild

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

parent.replaceChild(newChild, oldChild);
Copy after login

节点关系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);
Copy after login

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

getAttribute

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

var value = element.getAttribute("id");
Copy after login

样式相关API

直接修改元素的样式

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

动态添加样式规则

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

window.getComputedStyle

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

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

getBoundingClientRect

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

var clientRect = element.getBoundingClientRect();
Copy after login

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

Summary of common JavaScript native DOM operation APIs

 

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

 

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