Summary js commonly used operating dom (dom js the operation API)

 Reprinted: https://www.haorooms.com/post/js_dom_api 

Foreword

Many students are used to operate jquery dom, so that when they use js operations, often powerless, this paper summarizes the common method of operation dom js for everyone to read! In fact, talking about js operating dom , I have a long, long time before articles related js jquery attribute of implementation , which encompasses a large part of js common method of operation dom, but not very systematic. Can not be said API, system today to sum up!

Find node API

document.getElementById: find an ID element, case-sensitive, if there are multiple results, only the first return;

document.getElementsByClassName: find elements based on the class name, the plurality of class names separated by spaces, to return a HTMLCollection. Note that compatibility IE9 + (inclusive). Further, not only the Document, getElementsByClassName method also supports other elements;

document.getElementsByTagName: find elements according to the label, all labels * indicates that the query returns a HTMLCollection.

document.getElementsByName: According element's name attribute lookup returns a NodeList.

document.querySelector: return a single Node, IE8 + (inclusive), more than the results of matches, return only the first.

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

document.forms: Get the current page all the form, return a HTMLCollection;

Node Creation API

createElement create elements:

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

CreateElement created by elements not part of the document object, it just created it, did not add to the html document, to call the appendChild or insertBefore methods such as adding it to an HTML document.

createTextNode create a text node:

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

cloneNode clone a node:

node.cloneNode (true / false), it receives a bool parameter to indicate whether replicon elements.

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

Cloning node does not clone event, unless the event is

 

This way binding, = xxx with addEventListener and node.onclick; how binding are not copied.

 

createDocumentFragment

This method is used to create a DocumentFragment, which is a document fragment, which represents a lightweight document is primarily used for temporary storage nodes, use it can greatly enhance the performance of many operations DOM.

Node API changes

1、appendChild

grammar:

parent.appendChild(child);

2、insertBefore

parentNode.insertBefore(newNode, refNode);

3、insertAdjacentHTML

//js谷歌浏览器,火狐浏览器,IE8+
el.insertAdjacentHTML('beforebegin', htmlString);

About insertAdjacentHTML, this relatively easy to use API, concrete can see: https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML

<!-- beforebegin -->
<p>
  <!-- afterbegin --> foo <!-- beforeend --> </p> <!-- afterend -->

4、Element.insertAdjacentElement()

Similar usage and above,

targetElement.insertAdjacentElement(position, element);

5、removeChild

removeChild used to delete the specified child node and returns the child node, syntax:

var deletedChild = parent.removeChild(node);

deletedChild points to delete a reference to a node, it still exists in memory, may be the next step. In addition, if the node is not removed its child nodes, then the error is reported. Delete nodes are usually so deleted:

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

6、replaceChild

replaceChild used to replace another node, a node Syntax:

parent.replaceChild(newChild, oldChild);

API node relations

1. Parent API

parentNode: parentNode Each node has a property that indicates parent element. Element parent node may be Element, Document, or a DocumentFragment;

parentElement: Returns the parent element of the element node, wherein the difference between parentNode, the parent node must be an element of Element, if not, null is returned;

2, API child relationship

children: a return to real-time HTMLCollection, child nodes are Element, IE9 does not support the following browsers;

childNodes: Returns a real-time NodeList, represents the child node list of elements, pay attention to the child node can contain text nodes, comment nodes, etc.;

firstChild: Returns the first child node, there is no return null, corresponding thereto there is a firstElementChild;

lastChild: Returns the last child, there is no return null, corresponding thereto there is a lastElementChild;

3, brotherhood type API

previousSibling: a node before the node, or null if not present. Note that it is possible to get the node is a text node or a comment node does not match expected to be deal with it.

nextSibling: After one of the nodes, and if not present or null. Note that it is possible to get the node is a text node, not as expected, to be deal with it.

previousElementSibling: before returning an element node, a node must be pre-Element, note the following browser does not support IE9.

nextElementSibling: After returning an element node, the node must be a Element, note the following browser does not support IE9.

Element Property type API

1, setAttribute provided to the element properties:

element.setAttribute(name, value);

Where name is the attribute name, value is the characteristic value. If the element does not contain this feature that will be created and assigned.

2、getAttribute

getAttribute returns the corresponding characteristic value of the specified attribute name, and if not, null is returned:

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

3、hasAttribute

var result = element.hasAttribute(name); var foo = document.getElementById("foo"); if (foo.hasAttribute("bar")) { // do something }

4、dataset

Beginning html data- acquisition of property, used as follows:

<div id="user" data-id="1234567890" data-user="johndoe" data-date-of-birth>John Doe</div> let el = document.querySelector('#user'); // el.id == 'user' // el.dataset.id === '1234567890' // el.dataset.user === 'johndoe' // el.dataset.dateOfBirth === '' el.dataset.dateOfBirth = '1960-10-03'; // set the DOB. // 'someDataAttr' in el.dataset === false el.dataset.someDataAttr = 'mydata'; // 'someDataAttr' in el.dataset === true

Style related API

1, to directly modify the elements of style

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

2, dynamically add style rules

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

3, classList Gets the style class

// div is an object reference to a <div> element with class="foo bar"
div.classList.remove("foo"); div.classList.add("anotherclass"); // if visible is set remove it, otherwise add it div.classList.toggle("visible"); // add/remove visible, depending on test conditional, i less than 10 div.classList.toggle("visible", i < 10 ); alert(div.classList.contains("foo")); // add or remove multiple classes div.classList.add("foo", "bar", "baz"); div.classList.remove("foo", "bar", "baz"); // add or remove multiple classes using spread syntax let cls = ["foo", "bar"]; div.classList.add(...cls); div.classList.remove(...cls); // replace class "foo" with class "bar" div.classList.replace("foo", "bar");

4、window.getComputedStyle

Only get to inline styles through element.sytle.xxx, the aid window.getComputedStyle can get all the styles applied to the element, IE8 or earlier does not support this method.

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

API access to relevant height

Js about the height of my face again Mu Courses Online also recorded a video, js / jQuery wide variety of high understanding and application .

Here mainly to talk about:

getBoundingClientRect

getBoundingClientRect to return the size of the element and position relative to the visual browser window is used as follows:

var clientRect = element.getBoundingClientRect();

clientRect is a DOMRect object that contains width, height, left, top, right, bottom, it is relative to the top of the window rather than the top of the document, scroll the page when their values ​​change will occur.

Guess you like

Origin www.cnblogs.com/c-x-a/p/11433071.html