JS study notes (12) DOM

JS study notes (12) DOM

Article directory

1. DOM

1.1 Document type

The Document type represents the type of the document node in the JS document, and the characteristics of the Document node:

  • nodeType is equal to 9
  • The nodeName value is "#document"
  • nodeValue is null
  • parentNode value is null
  • ownerDocument value is null

 

1.2 DOM tree

  • Document: A page is a document, which is represented by document in DOM
  • Element: All tags in the page are elements, which are represented by element in DOM
  • Node: **All content** in a web page is a node (label, attribute, text, comment, etc.), which is represented by node in DOM

Note: DOM treats the above content as objects

 

1.3 Get document sub-node body and html

(1) Get body

document.body

(2) Get html

document.documentElement
let html = document.documentElement;
console.log(html === document.childNodes[0]); //true
console.log(html === documentfirstChild); //true

 

1.4 Document Information

Provides information about web pages loaded by the browser

Attributes are: title, URL, domain, referrer

  • URL: the URL in the address bar
  • domain: the domain name of the containing page
  • referrer: contains the URL of the page that links to the current page

 

1.5 Get elements

Ways to get elements:

  • Get by ID
  • Get by tag name
  • Obtained by the new method of HTML5
  • Special element acquisition

 

1.5.1 Get by ID

Obtained by getElementsById()

 

1.5.2 Obtain by tag name

Obtained by getElementsByTagName() , returns a NodeList containing zero or more elements

Get all elements in the document:

let allElement = document.getElementByTagName("*");

 

1.5.3 The newly added acquisition method of HTML5

  • getElementsByClassName
document.getElementsByClassName('类名');
  • querySelector 和 querySelectorAll
document.querySelector('选择器'); //根据指定的选择器返回第一个元素对象
document.querySelectorAll('选择器');//根据指定的选择器返回所有元素对象
  • matches()

Returns true if the element matches the selector, otherwise returns false

if (document.body.matches("body.page1")) {
    
    
    // true
}

 

1.6 Special Collections

  • document.anchors: contains all the name attributes in the document<a>
  • document.forms: Contains all form elements in the document
  • document.images: Contains all img elements in the document
  • document.links: Contains all elements with href attributes in the document

 

1.7 Document writing

Write content to the web page input stream: write(), writeln(), open(), close().

  • write() simply writes text, and writeln() appends a newline to the end of the string.
  • write() and writeln() are often used to dynamically include external resources

 

2. Node

Nodes have at least nodeType, nodeName and nodeValue properties

2.1 Node type

       Each node has a nodeType attribute, indicating the type of the node, and the node type is represented by 12 numerical constants defined on the Node type:

  • Node.ELEMENT_NODE(1) element node
  • Node.ATTRIBUTE_NODE(2) attribute node
  • Node.TEXT_NODE(3) Text node (contains text, spaces, newlines, etc.)
  • Node.CDATA_SECTION_NODE(4)
  • Node.ENTITY_REFERENCE_NODE(5)
  • Node.ENTITY_NODE(6)
  • Node.PROCESSING_INSTRUCTION_NODE(7)
  • Node.COMMENT_NODE(8)
  • Node.DOCUMENT_NODE(9)
  • Node.DOCUMENT_TYPE_NODE(10)
  • Node.DOCUMENT_FRAGMENT_NODE(11)
  • Node.NOTATION_NODE(12)

 

2.1.1 nodeName 和 nodeValue

       nodeName and nodeValue hold information about the node. The values ​​of these two properties depend entirely on the type of the node, it is best to check the node type before using it

 

2.2 Node relationship

       Each node has a childNodes property, which contains an instance of NodeList. The ownerDocument property is a pointer to the document node that represents the entire document. is a relationship shared by all nodes

 

2.3 Node operation

 

2.3.1 Operation of parent node

child node object.parentNode

 

2.3.2 Operation of child nodes

basic operation
1.parentNode.childNodes

       Returns the set of child nodes containing the specified node. The return value contains all child nodes, including element nodes, text nodes, etc. If you only want to get the element nodes inside, you need to further process, so generally do not use childNodes
 

2.parentNode.children

       parentNode.children is a read-only property that returns all child element nodes , only child element nodes are returned, and others are not returned.

Get the first child element and the last child element
3..parentNode.firstChild
4.parentNode.lastChild

The above two methods include all nodes

5.parentNode.firstElementChild

Only return the first child element node, if not found, return null

6.parentNode.lastElementChild

firstElementChild and lastElementChild have compatibility issues.

 
A better solution (actually developed writing)

There will be no compatibility issues and the first child element can be returned

parentNode.children[0]

 

2.3.3 Brother nodes

1.node.nextSibling

Returns the next sibling node of the current element, including all nodes

2.node.previousSibling

Returns the previous sibling node of the current element, including all nodes

3.node.nextElementSibling

Returns the next sibling element node of the current element

4.node.previousElementSibling

Also these two methods have compatibility issues

 
solution:

Encapsulate a compatibility function yourself

function getNextElementSibling(element) {
    
    
    var el = element;
    while (el = el.nextSibling) {
    
    
        if (el.nodeType === 1) {
    
    
            return el;
        }
    }
    return null;
}

 

2.3.4 Creating Nodes

document.createElement('tagName')

The created element did not exist originally and was dynamically generated according to the requirements, so it is also called dynamically created element node

 

2.3.5 Adding Nodes

1.node.appenChild(child)

       Adds a node to the end of the list of children of the specified parent node

       If a node that already exists in the document is passed to appendChild(), the node will be transferred from the previous position to the new position . That is, if appendChild() is called to pass in the first node of the parent element, this node will become the last node of the parent element

//假设someNode有多个节点
let returnedNode = someNode.appendChild(someNode.firstChild);
alert(returnedNode == someNode.firstChild);//false
alert(returnedNode == lastChild);//true
2.node.insertBefore(child,指定元素)

Add a node before the specified child node of the specified parent node

 

2.3.6 Delete Node

node.removeChild(child)

Removes a child node from the DOM, returns the removed node

 

2.3.7 Duplicate nodes

node.cloneNode()

Returns a copy of the node calling this method, also known as clone node/copy node

Notice:

  • If the parentheses are empty or false , it is a shallow copy , and only the node itself is copied, and the child nodes inside are not cloned
  • If the parenthesis parameter is true , it is a deep copy , which will copy the node itself and all child nodes inside

 

2.4 Element type (element)

Node characteristics of the Element type:

  • nodeType is equal to 1
  • nodeName value is the tag name of the element
  • nodeValue equals null
  • The value of parentNode is Document or Element object
  • Child nodes can be Element, Text, Comment, ProcessingInstruction, CDATASection, EntityReference types

The tag name of the element can be obtained through the nodeName or tagName attribute, but note that div.tagName returns "DIV" instead of "div". In HTML, element tag names are always expressed in all uppercase.

 

2.4.1 Get property value

  • element.attribute
  • element.getAttribute('attribute');

the difference:

  • element.property: get the built-in property value (property that comes with the element)
  • element.getAttribute('attribute'): Mainly get custom attributes

 

2.4.2 Setting property values

  • element.property = 'value' set built-in property value
  • element.setAttribute('attribute', 'value'); mainly for custom attributes
div.id = 'test';
div.className = 'navs';

div.setAttribute('index',2);
div.setAttribute('class','footer'); //这里写的是class 不是className

Note: the way class is written in the two methods

 

2.4.3 Remove attributes

removeAttribute(attribute);

 

2.4.4 Custom properties

Purpose: In order to save and use data, some data can be saved to the page instead of to the database.

Custom attributes are obtained through getAttribute('attribute')

1. Set H5 custom attributes

H5 stipulates that custom attributes start with **data-** as attribute names and assign values

<div data-index= '1'></div>
//或使用JS设置
element.setAttibute("data-index",2);
<div getTime="20" data-index="2" data-list-name="niki"></div>
<script>
    var div = document.querySelector("div");
    console.log(div.dataset.listName);
    console.log(div.dataset["listName"]);
</script>
  • dataset is a collection that stores all custom attributes starting with data
  • If there are multiple - linked words in the custom attribute, we use camel case naming method when obtaining

 

2. Get H5 custom attributes

  • Compatibility acquisition: element.getAttribute('data-index');
  • H5 added element.dataset.index or element.dataset['index'] IE11 only began to support

 

2.4.5 attribute attribute

       Element is the only DOM node type that uses the attribute attribute. The attribute attribute contains a NamedNodeMap instance, which contains the following methods:

  • getNamedItem(name): returns the node whose nodeName attribute is equal to name
  • removeNamedItem(name): delete the node whose nodeName attribute is equal to name
  • setNamedItem(node): Add a node node to the list, indexed by its nodeName
  • item(pos): returns the node at the index position pos

       The nodeName of each node in the attributes attribute is the name of the corresponding attribute, nodeValue is the value of the attribute, such as the value of the id attribute of the element to be

let id = element.attributes.getNamedItem("id").nodeValue;
let id = element.attributes.getNamedItem["id"].nodeValue;

 

2.4.6 Form property setting

Case: imitating Jingdong to display hidden passwords

  1. Core idea: click the eye button, change the type of the password box to a text box, and you can see the password inside
  2. One button has two states, click once to switch to a text box, continue to click once to switch to a password box
  3. Algorithm: Use a flag traversal to judge the value of the flag. If it is 1, it will switch to a text box, and the flag is set to 0. If it is 0, it will switch to a password box, and the flag is set to 1.
let eye = document.getElementById("eye");
let pwd = document.getElementById("pwd");
// 注册事件处理程序
let flag = 0;
eye.addEventListener("click", () => {
    
    
  // 点击一次后,flag一定变化
  if(flag == 0) {
    
    
    pwd.type = 'text';
    eye.src = 'images/open.png';
    flag = 1;
  } else {
    
    
    pwd.type = 'password';
    eye.src = 'images/close.png';
    flag = 0;
  }
})

 

2.4.7 Modify style

1.element.style       行内样式操作
2.element.className   类名样式操作

Notice:

  • The style in JS adopts camel case naming method , such as: fontSize
  • JS modifies the style operation to generate an inline style , and the weight of css is relatively high
  • If there are many styles , you can change the element style by manipulating the class name
  • Because class is a reserved word, use className to operate the element class name attribute
  • className will directly change the class name of the element and will overwrite the original class name

 

2.5 Text type

Characteristics of nodes of type Text:

  • nodeType is equal to 3
  • nodeName value is "#text";
  • nodeValue is the text contained in the node
  • parentNode value is Element object

       The text contained in the Text node can be accessed through the nodeValue property and also through the data property, both properties contain the same value
 

2.5.1 Creating text nodes

document.createTextNode()

 

2.5.2 Normalizing Text Nodes

normalize()

Used to merge adjacent text nodes.

let element = document.createElement("div");
element.className="mes";
let textNode = document.createTextNode("hello world!");
element.appendChild(textNode);

let anotherTextNode = document.createTextNode("niki");
element.append(anotherTextNode);

document.body.appendChild(element);
alert(element.childNodes.length); //2
element.normalize();
alert(element.childNodes.length);//1
alert(element.firstChild.nodeValue)//"hello world!niki"

 

2.5.3 Splitting Text Nodes

splitText()

This method splits nodeValue at the specified offset, splitting a text node into two text nodes

 

3. DOM programming

3.1 NodeList

NodeList is a real-time query based on DOM documents. The following behaviors will cause an infinite loop:

let divs = document.getElementsByTagName("div");
for (let i = 0; i < divs.length; ++i) {
    
    
    let div = document.createElement("div");
    document.body.appendChild(div)
}

solution:

let divs = document.getElementsByTagName("div");
for (let i = 0, len = divs.length; i < len; ++i) {
    
    
    let div = document.createElement("div");
    document.body.appendChild(div)
}

 

Four, MutationObserver interface

       The MutationObserver interface can execute callbacks asynchronously when the DOM is modified . Use MutationObserver to observe the entire document, a part of the DOM tree or an element. In addition, you can observe changes in element attributes, child nodes, text, or any combination of the first three

4.1 Basic usage

       Instances of MutationObserver are created by calling the MutationObserver constructor and passing in a callback function

let observer = new MutationObserver(() => console.log("DOM is mutataed!"));

1. observer()

       The newly created MutationObserver instance will not be associated with any part of the DOM, and the observer must be used to associate with the DOM. observer() receives two necessary parameters: the DOM node to observe its changes, and a MutationObserver object ( used to control which changes to observe, which is a dictionary of configuration options in the form of key-value pairs )

let observer = new MutationObserver(() => console.log("<body> attributes changed!"))
observer.observe(document.body,{
    
    attributes:true});

document.body.className ='foo';
console.log('changed body class');
//changed body class
//<body> attributes changed!

       Executed after the console in the callback, indicating that the callback is not synchronized with the actual DOM changes.

 

2. Callback and MutationRecord

       Each callback receives an array of MutationRecord instances enqueued in order. MutationRecord instances contain information about what mutations occurred and which part of the DOM was affected. , the second parameter passed to the callback function is the MutationObserver instance that observes the change

let observer = new MutationObserver(
	(mutationRecords) => console.log(mutationRecord));

 

3. disconnect()

       By default, as long as the observed element is not garbage collected, the callback of MutationObserver will be executed in response to the DOM change event. To terminate the execution of the callback in advance, you can use disconnect(). This method will not only stop the callback of subsequent change events, but also discard the callback that has been added to the task queue to be executed asynchronously:

let observer = new MutationObserver(() => console.log("<body> attributes changed!"))
observer.observe(document.body,{
    
    attributes:true});

document.body.className = 'foo';
observer.disconnect();
observer.body.className = 'bar';
// 无日志输出

       If you want to execute the callbacks that have been added to the task queue, you can use setTimeout() to let the callbacks that have been enqueued be executed before calling disconnect()

let observer = new MutationObserver(() => console.log("<body> attributes changed!"))
observer.observe(document.body,{
    
    attributes:true});

document.body.className = 'foo';
setTimeout(() => {
    
    
    observer.disconnect();
	observer.body.className = 'bar';
},0)
// <body> attributes changed!

 

4. Reuse MutationObserver

       By calling observe() multiple times, one MutationObserver object can be used to observe multiple different target nodes. At this point, the target attribute of MutationRecord can identify the target node of the change event

let observer = new MutationObserver(
    (mutationRecords) => console.log(mutationRecords.map((x) => x.target)));
let childA = document.createElement("div");
let childB = document.createElement("span");
document.body.appendChild(childA);
document.body.appendChild(childB);

// 观察两个节点
observer.observe(childA, {
    
    attributes:true});
observer.observe(childB, {
    
    attributes:true});

// 修改两个节点的属性
childA.setAttribute("foo","bar");
childB.setAttribute("foo","bar");

 

5. Reuse MutationObserver

       Calling disconnect() will not end the life of MutationObserver, you can also reuse this observer and associate it with a new target node

let observer = new MutationObserver(() => console.log("<body> attributes changed!"))
observer.observe(document.body,{
    
    attributes:true});

document.body.setAttribute("foo","bar") // 触发事件
setTimeout(() => {
    
    
    observer.disconnect();
    document.body.setAttribute("bar","baz"); // 不会触发事件
},0);

setTimeout(() => {
    
    
    observer.observe(document.body,{
    
    attributes:true});
    document.body.setAttribute("baz","qux"); // 触发事件
},0);

 

4.2 MutationObserverInit and observation scope

       The MutationObserverInit object is used to control the observation range of the target node, and the observed things include attribute changes, text changes and child node changes

 

4.3 Asynchronous callback and record queue

1. Record queue

       Every time MutationRecord is added to the record queue of MutationObserver, only when there is no scheduled microtask callback before, the callback registered by the observer will be dispatched to the task queue as a microtask, which can ensure that the content of the record queue is not will be processed twice by the callback

 

2. takeRecords()

takeRecords() can clear the record queue, remove and return all MutationRecord instances in it

 

5. HTML5

5.1 CSS Class Extensions

5.1.1 getElementByClassName()

See 1.5.3

 

5.1.2 ClassList property

1. Naive operation (not recommended)

       The addition, deletion and replacement of class names can be realized through className. className is also a string, so this value must be reset after each operation to take effect

<div class="bd user disable"></div>

       This div has 3 class names. If you want to delete one of them, you have to take apart the className first, delete the unwanted one, and then set back the string containing the remaining classes:

// 要删除的类
let targetClass = 'user';
// 把类名拆成数组
let classNames = div.className.split(/\s+/);
// 找到要删除类名的索引
let idx = classNames.indexOf(targetClass);
// 若有就删除
if(idx>-1) {
    
    
    classNames.splice(idx,1);
}
// 重新设置类名
div.className = classNames.join(" ");

 

2. Advanced operation (recommended)

       className is an instance of a new collection type DOMToken, which has a length property and the following methods:

  • add(value): Add the specified class name (string) value to the similar class name list, if the value already exists, do nothing
  • contains(value): Returns a Boolean value indicating whether the given value exists
  • remove(value): Remove the specified string value value from the list of class names
  • toggle (value): If the specified value already exists in the class name list, delete it, and add it if it does not exist

 

5.2 Focus Management

5.2.1 document.activeElement

       document.activeElement always contains the currently focused DOM element. When the page loads, an element can be automatically focused by user input (press the Tab key or use focus() in the code)

       By default, document.activeElement will be set to document.body just after the page is loaded. Before Mina is fully loaded, the value of document.activeElement is null

 

5.2.2 document.hasFocus

Returns a boolean indicating whether the document has focus

 

5.3 HTMLDocument extension

1. readyState property

Two values ​​for the document.readyState property:

  • loading: Indicates that the document is loading
  • complete: Indicates that the document loading is complete

 

2. compatMode attribute

       Indicates what rendering mode the browser is currently in. In standard mode, the value of document.compatMode is "CSS1Compat", and in mixed mode, the value of document.compatMode is "BackCompat"

 

3. head attribute

HTML5 adds document.head attribute, pointing to<head>

 

5.5 Custom data attributes

See 2.4.4

 

5.6 Inserting markers

1. innerHTML attribute

       When innerHTML is read, the HTML string for all descendants of the element is returned, including elements, comments, and text nodes. (including html tags, while preserving spaces and newlines)

       When writing innerHTML, all nodes originally contained in the element will be replaced with a new DOM subtree according to the provided string value. If the assignment does not contain any HTML tags, a text node is generated directly

       The actual returned text content will vary depending on the browser. IE and Opera will convert all elements to uppercase, while Safari, Chrome and Firefox will return them in the format of the source code

       Although innerHTML will not execute the one created by itself <script>, it still exposes a large attack surface to malicious users. If the information provided by the user is to be used in the page, it is recommended not to use innerHTML to prevent XSS attacks.

 

The difference between the three dynamically created elements

  • document.write()
  • element.innerHTML
  • document.createElement()

the difference:

  1. document.write() : is the content stream that writes content directly to the page. But when the document flow is executed, it will cause the page to be completely redrawn

  2. innerHTML : It is to write the content to a DOM node, which will not cause the entire page to be redrawn. It is more efficient to create multiple elements, do not concatenate strings, use arrays to concatenate , and the structure is slightly more complicated

    function foo(){
          
          
        var d1 = +new Date();
        var arrry = [];
        for(var i=0;i<1000;i++) {
          
          
            arrry.push('<div style="width:100px;height:2px;border:1px solid blue;"></div>')
        }
        document.body.innerHTML = arrry.join('');
        var d2 = +new Date();
        console.log(d2-d1);
    }
    foo();
    
  3. document.createElement(): Creating multiple elements is slightly less efficient, but the structure is clearer

    function foo(){
          
          
        var d1 = +new Date();
        var arrry = [];
        for(var i=0;i<1000;i++) {
          
          
            var div = document.createElement('div');
            div.style.width = '100px';
            div.style.height = '2px';
            div.style.border = '1px solid red';
            document.body.appendChild(div);
        }
        var d2 = +new Date();
        console.log(d2-d1);
    }
    foo();
    

 

2. outerHTML attribute

       When the outerHTML property is read, it returns the HTML string of the element that called it (itself and all descendant elements).

       When writing outerHTML, the element calling it will be replaced by the DOM subnumber generated after the incoming HTML string is interpreted

 

3. insertAdjacentHTML()与insertAdjacentText()

       Both methods receive two parameters: the location to insert the markup and the HTML or text to insert.

       The first parameter must be one of the following values ​​(values ​​are not case sensitive):

  • "beforebegin": Insert in front of the current element as the previous sibling node
  • "afterbegin": Insert inside the current element, as a new child node or before the first child node
  • "beforeend": Insert inside the current element, as a new child node or after the last child node
  • "afterend": Insert after the current element as the next sibling node

        The second argument will be parsed as an HTML string (same as innerHTML and outerHTML) or as plain text (same as innerText and outerHTML)

 

5.7 scrollIntoView()

The browser window or container element can be scrolled so that the containing element fits into the viewport with the following parameters:

  • alignToTop(boolean):
    • true: The top of the element is aligned with the top of the viewport after the window is scrolled
    • false: The bottom of the element is aligned with the bottom of the viewport after the window is scrolled
  • scrollIntoViewOptions is a selection object
    • behavior: define the transition animation, the possible values ​​are "smooth" and "auto", the default is "auto"
    • block: defines the alignment in the vertical direction, which can be "start" (default), "center", "end" and "nearest"
    • inline: defines the alignment in the horizontal direction, which can be "start", "center", "end" and "nearest" (default)
  • Not passing parameters is equivalent to alignToTop is true

 

6. Proprietary extension

       Refers to the proprietary extensions added to the DOM by various browser vendors to make up for the lack of functionality that has not been standardized (entering HTML5)

6.1 children attribute

       The children attribute is an HTMLCollection that only contains child nodes of the Element type of the element

 

6.2 contains()

       Determines whether an element is a descendant of another element,

       DOM Level 3's compareDocumentPosition() can also determine the relationship between nodes. This method returns a bitmask representing the relationship between the two nodes

mask node relationship
0x1 disconnected (the node passed in is not in the document)
0x2 leading (the passed in node precedes the reference node in the DOM tree)
0x4 Subsequent (the passed in node comes after the reference node in the DOM tree)
0x8 contains (the node passed in is an ancestor of the reference node)
0x10 is contained (the node passed in is a descendant of the reference node)

 

6.3 Inserting markers

1. innerText

All text content         contained within the corresponding element . When reading the value, innerText will concatenate all the text values ​​in the subnumber in depth-first order. When writing a value, innerText removes all descendants of the element and inserts a text node containing the value . (Remove html tags, and spaces and newlines will also be removed)

div.innerText = 'Hello world!';
<div id='content'>Hello world!</div>
  • Setting innerText will remove all descendant nodes before the element, completely changing the DOM subtree
  • Setting innerText will encode HTML syntax characters (greater than and greater than signs, quotation marks and ampersands) that appear in the string
  • By setting innerText equal to innerText, all HTML tags can be stripped leaving only text

 

The difference between InnerText and InnerHtml

innerText:

  • does not recognize html tags
  • The content inside the element can be obtained
  • will remove spaces and newlines

innerHtml:

  • Identify html tags
  • The content inside the element can be obtained
  • Preserve spaces and newlines

 

2. outerText

       Scope includes the node calling it

       When reading text, outerText and innerText actually return the same content.

       When writing a text value, outerText will not only remove all descendant nodes, but replace the entire element

       

Seven, DOM2 and DOM3

7.1 Evolution of DOM

       The goal of the core module for DOM2 and DOM3: to extend the DOM API to meet all the needs of XML and provide better error handling and feature detection.

       DOM2 core does not add any new types, but only adds some methods and properties on the basis of DOM1 core.

       DOM 3 core not only enhances the original types, but also adds new types

       

7.1.1 XML namespaces

       The XML namespace can realize the mixing of different XML languages ​​in a standardized document without worrying about element naming conflicts. Strictly speaking, XML namespaces are only supported in XHTML, not in HTML.

       XML namespaces are specified using xmlns. The XHTML namespace is "http://www.w3.org/1999/xhtml" and should be included in any well-formed XHTML page <html>:

<html xmlns="http://www/w3.org/1999/xhtml" lang="en">
    <head>
        <title>Document</title>
    </head>
    <body>
        hello!
    </body>
</html>

       For the above example, all elements belong to the XHTML namespace by default. You can use xmlns to create a prefix for the namespace in the format: "xmlns:prefix".
       If only one XML language is used in the document, the namespace prefix is ​​actually redundant, and it is only necessary when a document mixes multiple XML languages. For example, the following document uses both XHTML and SVG languages:

<html xmlns="http://www/w3.org/1999/xhtml" lang="en">
    <head>
        <title>Document</title>
    </head>
    <body>
        <svg xmlns="http://www.w3/org/2000/svg" version="1.1">
            <rect x="0" y="0" width="100" style="fill: red;"/>
        </svg>
    </body>
</html>

       

1. Changes in Node

In DOM2, the Node type contains the following namespace-specific properties:

  • localName: node name without namespace prefix
  • namespcaeURI: Namespace URL of the node, null if not specified
  • prefix: namespace prefix, null if not specified

DOM3 adds the following methods:

  • isDefaultNamespace(namespaceURI): Returns a Boolean value indicating whether namespaceURI is the default namespace of the node
  • lookupNamespaceURI(prefix): Returns the namespace URI for the given prefix
  • lookupPrefix(namespaceURI): returns the prefix for the given namespURI

       

2. Document changes

DOM2 adds the following namespace-specific methods on the document type:

  • createElementNS(namespaceURI, tagName): Create a new element of the specified namespace namespaceURI with the given tag name tagName
  • createAttributeNS(namespaceURI, attibuteName): Create a new attribute of the specified namespace namespace URI with the given attribute name attibuteName.
  • getElementByTagNameNS(namespaceURI, attibuteName): Returns the NodeList of all elements with the tag name tagName in the specified namespace namespaceURI

       

3. Element changes

  • getAttributeNS
  • getAttributeNodeNS
  • getElementByTagNameNS
  • hasAttributeNS
  • removeAttributeNS
  • setAttributeNS
  • setAttributeNodeNS

       

7.1.2 Other changes

1. DocumentType change

        DocumentType adds 3 new attributes: publicId, systemId and internalSubset

       

2. Document changes

  • importNode: Get a node from another document and import it into the new document.
  • createDocumentType(): Create a node of type DocumentType
  • createDocument(): create a new document
  • createHTMLDocument(): Create a complete HTML document

       

3. Node changes:

DOM3 adds two new methods for comparing nodes: isSameNode() and isEqualNode():

  • isEqualNode(): The nodes are the same, i.e. refer to the same object
  • isSameNode(): The nodes are equal, that is, the nodes are of the same type, have equal attributes, and attributes and childNodes are also equal

       DOM3 also added a method to attach additional data to DOM nodes: setUserData(). This method receives 3 parameters: key, value, and processing function. Handlers are executed when a node containing data is assigned, deleted, renamed, or imported into another document

       

4. Changes to embedded panes

       DOM2 <iframe>adds a new attribute to HTMLIFrameElement: contentDocument . This property contains a pointer to a document object that represents the content of the sub-embedded pane.

       There is also an attribute contentWindow , which returns the window object of the corresponding pane, and there is a document object

       

7.2 Style

Three ways to define styles:

  • external stylesheet ( <link>)
  • Document Style Sheet ( <style>)
  • Element-specific styles (style attribute)

       

7.2.1 Accessing element styles

       CSS attribute names use hyphen notation, and these attributes must be converted to camel case in JS (note: float cannot be converted, which is a reserved word in JS):

background-image -------> style.backgroundImage

1. DOM style properties and methods

  • cssText: contains the css code in the style attribute

  • length: the number of CSS properties applied to the element, together with item() to iterate CSS properties

  • parentRule: CSSRule object representing CSS information

  • getPropertyPriority(propertyName): If the CSS property is used! important, returns "important", otherwise returns an empty string

  • getPropertyValue(propertyName): returns the string value of the property propertyName

  • item(index): returns the CSS property name whose index is index

    style[i] = style.item(i)

  • removeProperty (propertyName): delete propertyName, using this method to delete a property means that the default style of the property will be applied

  • setProperty(propertyName, value, priority): Set the value of the CSS property propertyName to value, priority is "important" empty string

       

2. Calculation style

       DOM2 Style Added getComputedStyle() on document.defaultView.

document.defaultView.getComputedStyle(myDiv,null);

       This method receives two parameters: **The element to get the calculated style and the pseudo-element string. **If you do not need to query pseudo-elements, you can pass null as the second parameter. getComputedStyle() returns a CSSStyleDeclaration object containing the element's computed style

       Note : Computed styles are read-only in all browsers, and the object returned by getComputedStyle() cannot be modified. And computed styles also contain information from the browser's internal styles. So CSS properties with default values ​​will appear in computed styles

       

7.2.2 Manipulating style sheets

CSSStyleSheet inherits properties from StyleSheet:

  • disabled: Whether the style sheet is disabled (readable and writable)

  • href: is <link>the included style sheet, returns the URL of the style sheet

  • media: a collection of media types supported by the style sheet

  • ownerNode: Points to the node that owns the current style sheet, either in <link>HTML <style>. If the current style sheet is included in another style sheet via @import, the value of this property is null

  • parentStyleSheet: If the current style sheet is included in another style sheet through @import, this attribute points to the style sheet that imported him

  • title: the title attribute of ownerNode

  • type: string, indicating the type of style sheet. A CSS style sheet is "text/css"

CSSStyleSheet also supports properties and methods:

  • cssRules: a collection of style rules contained in the current style sheet
  • ownerRule: Points to the import rule if the stylesheet was imported using @import. otherwise null
  • deleteRule(index): Delete the rules in cssRules at the specified position
  • insertRule(rule, index): Insert rules into cssRules at the specified position

       document.styleSheet represents the collection of style sheets available in the document. The length property of this collection holds the number of style sheets in the document, and each style sheet can be obtained using square brackets or item()

       

7.2.3 Element size

1. Offset size

The offset size contains all the visual space        the element occupies on the screen . Visual space consists of height-width, including **all padding, scrollbars, and borders (not margins). There are 4 properties that can be used to get the offset size of the element:

  • offsetHeight: The pixel size occupied by the element in the vertical direction, including its height, the height of the horizontal scroll bar, and the height of the upper and lower borders
  • offsetLeft: The outer distance of the left border of the element contains the number of pixels measured inside the left border of the element
  • offsetTop: The distance outside the top border of the element includes the number of pixels measured inside the top border of the element
  • offsetWidth: The pixel size occupied by the element in the horizontal direction
  • offsetParent: Returns the parent element with positioning as the element, or returns body if the parent element is not positioned

Notice:

  1. offsetLeft and offsetTop are relative to the containing element
  2. Returns values ​​without units

 
       To determine an element's offset within the page, add its offsetLeft and offsetTop properties to the same properties of offsetParent, respectively, up to the root element :

function getElementLeft(element) {
    
    
    let actualLeft = element.offsetLeft;
    let current = element.offsetParent;

    while (current != null) {
    
    
        actualLeft += current.offsetLeft;
        current = current.offsetParent;
    }
    return actualLeft;
}
The difference between style and offset

insert image description here

       

2. Client size

       The client size includes the space occupied by the element content and its padding . The attributes are: clientWidth and clientHeight. The client-side size is actually the space inside the element, so it doesn't include the space occupied by scrollbars. These two properties are often used to determine the browser viewport size

       

3. Scroll size

Provides information about the scrolling distance of the element content. The attributes are:

  • scrollHeight: The total height of the element content when no scrollbar appears
  • scrollWidth: When no scroll bar appears, the total width of the element content
  • scrollLeft: The number of hidden pixels on the left side of the content area. Setting this property can change the scrolling position of the element. The default is 0
  • scrollTop: The number of hidden pixels at the top of the content area, setting this property can change the scrolling position of the element, the default is 0

 

4. Summary of the three dimensions

Comparison of three sizes effect
offsetWidth Returns itself including padding, the width of the content area, and the border, and the returned value does not have a unit
clientWidth Returns itself including padding, the width of the content area, excluding borders , and returns values ​​without units
scrollWidth Returns the actual width of itself, without borders , and returns values ​​without units

Main usage:

  1. The offset series is often used to obtain the element position offsetLeft offsetTop
  2. The client series is often used to get the element size clientWidth clientHeight
  3. scroll is often used to get the scrolling distance
  4. The main page scrolling distance is obtained through window.pageXOffset
           

5. Determine element size

       The browser exposes getBoundingClientRect() on each element, returning a DOMRect object with 6 properties: left, top, right, bottom, height, and width

       

7.3 Traversal

       Two types used to assist sequential traversal of the DOM structure, performing a depth-first traversal of the DOM structure from a starting point: NodeIterator and TreeWalker

       

7.3.1 Node Iterator

Create an instance through document.createNodeIterator () and receive 4 parameters:

  • root: as the node to traverse the root node

  • whatToShow: Numerical code indicating which nodes should be visited, which is a bit mask, specifying which nodes to visit by referring to one or more filters

  • filter, NodeFilter object or function: indicates whether to receive or skip a specific node, the filter function of the node

    The NodeFilter object has only one method accpectNode(), if the given node should be accessed, return NodeFIlter.FILTER_ACCEPT, otherwise return NodeFIlter.FILTER_SKIP

  • entityReferenceExpansion: Boolean value, indicating whether to expand the entity reference

<p>Example: To define your filter object that only accepts elements:

let filter = {
    
    
    acceptNode(node) {
    
    
        return node.tagName.toLowerCase() == "p"? NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP;
    }
};
//filter还可以是函数,下面的写法与上面的等价
let filter = function(node){
    
    
    return node.tagName.toLowerCase() == "p"? NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP;
}

let iterator = document.createNodeIterator(root,NodeFilter.SHOW_ELEMENT,filter,false);

       

nextNode()和 previousNode()

The main method of NodeIterator, the difference:

  • nextNode(): Go one step forward in the DOM subtree in a depth-first manner, the first call returns the root node. Returns null when traversing to the last node of the DOM tree
  • previousNode(): Go back one step in the traversal. When traversing to the last node of the DOM tree, return the traversed root node

Example: Traverse all elements in a div

<div id="div1">
    <p><b>HELLO</b> WORLD!</p>
    <ul>
        <li>List item 1</li>
        <li>List item 2</li>
        <li>List item 3</li>
    </ul>
</div>
let div = document.getElementById("div1");
let iterator = document.createNodeIterator(div,NodeFilter.SHOW_ELEMENT,null,false);
let node = iterator.nextNode();
while(node!=null){
    
    
    console.log(node.tagName);
    node = iterator.nextNode();
}

       

7.3.2 TreeWalker

       TreeWalker is an advanced version of NodeIterator, created with document.createTreeWalker() , similar to NodeIterator, and can usually replace NodeIterator.

The filter of TreeWalker has three return values:

  • NodeFilter.FILTER_ACCEPT
  • NodeFilter.FILTER_SKIP: Skip the node and visit the next node in the subtree
  • NodeFilter.FILTER_REJECT: Indicates skipping the node and the entire subtree of the node

        Added parentNode(), firstChild(), lastChild(), nextSibling() and previousSibling() in addition to nextNode() and previousNode()

       The TreeWalker type has a currentNode property, indicating the node returned last time during the traversal. You can modify this property to affect the starting point of the next traversal

       

7.3.3 Element traversal

DOM elements have 5 attributes:

  • childElementCount: returns the number of child elements (excluding text nodes and comments)
  • firstElementChild: Points to the first child element of Element type (firstElementChild version: firstChild)
  • lastElementChild: points to the last child element of Element type (firstElementChild version: lastChild)
  • previousElementSibling: Points to the sibling element of the previous Element type (firstElementChild version: previousSibling)
  • nextElementSibling: Points to the sibling element of the next Element type (firstElementChild version: nextSibling)

The difference between firstElementChild and firstChild:

  • firstElementChild must return the element node
  • firstChild does not necessarily return element nodes

Example: Iterating over all child elements of a specific element

let parentElement = document.getElementById('parent');
let currentChildElement = parentElement.firstElementChild;

while(currentChildElement) {
    
    
    // 获得元素节点
    processChild(currentChildElement);
    if(currentChildElement == parentElement.lastChild) {
    
    
        break;
    }
    currentChildElement = currentChildElement.nextElementSibling;
}

       

7.4 DOM scope

       document.createRange() can create a DOM range object. This newly created range object is associated with the document that created it and cannot be used in other documents. Related methods and properties:

  • startContainer: the node where the range starts (the parent node of the first child node in the selection)
  • startOffset: The offset of the start of the range in startContainer. If startContainer is a text node, comment node or CData block, then startOffset refers to the number of skipped characters at the beginning of the range; otherwise, it indicates the index of the first node in the range.
  • endContainer: the node at the end of the range (the parent node of the last node in the selection)
  • endOffset: The offset of the startContainer of the range start point.
  • commonAncestorContainer: The deepest node of the document with startContainer and endContainer as descendants.

       

7.5 Selection

7.5.1 Simple selection

       selectNode() and selectNodeContents() : Select a part of the document by range. Both methods receive a node as a parameter and add information about that node to the scope in which it is called. selectNode() selects the entire node, including its descendant nodes , while selectNodeContents() selects only the node's descendants .

<p id="p1"><b>hello</b> world!</p>
let range1 = document.createRange(),
    range2 = document.createRange(),
    p1 = document.getElementById("p1");
range1.selectNode(p1);
range2.selectNodeContents(p1);

 
For more fine-grained scope control:

  • setStartBefore(refNode)
  • setStartAfter(refNode)
  • setEndBefore(refNode)
  • setEndAfter(refNode)

       

7.5.2 Complex selection

       setStart() and setEnd(). For setStart(), the reference node becomes startContainer, and the offset is assigned to startOffset. For setEnd(), the reference node will become endContainer, and the offset will be paid to endOffset

       

Eight, DOM operation summary

Regarding DOM operations, it is mainly to create, add, delete, modify, check, attribute operations, event operations

(1) Create

  • document.write
  • innerHTML
  • createElement

(two) increase

  • appenChild
  • insertBefore

(3) delete

  • removeChild

(4) change

  • Modify the attributes of elements: src, href, title, etc.
  • Modify the content of common elements: innerHTML, innerText
  • Modify form elements: value, type, disabled, etc.
  • Modify element style: style, className

(five) check

  • API methods provided by DOM: getElementById, getElementsByTagName old methods are not recommended
  • New methods provided by H5: querySelector, querySelectorAll advocated
  • Use nodes to get elements: parent (parentNode), child (children), brother (previousElementSibling, nextElementSibling) Advocate

(6) Attribute operation

Mainly for custom attributes

  • setAttribute: Set the DOM attribute value
  • getAttribute: Get DOM attribute value
  • removeAttribute : remove the attribute value

(7) Event operation

Guess you like

Origin blog.csdn.net/weixin_45950819/article/details/120636274