js Advanced Programming Notes 7--DOM2 and DOM3

Keywords: Attribute html5 Firefox IE

Selector API

Selectors API is a standard initiated by W3C. Committed to making the browser native support CSS query.

querySelector() method

This method receives a CSS selector and returns the first element that matches the pattern. If no return null is found.

var body = document.querySelector("body");
var myDiv = document.querySelector("#myDiv");
var selected = document.querySelector(".selector");
var img = document.body.querySelector("img.button");

If an unsupported selector is passed in, the querySelector() method throws an error.

querySelectorAll() method

The parameters received are the same as the querySelector() method, but an instance of NodeList is returned.

//Get all < strong > elements in all < p > elements
var strongs = document.querySelectorAll("p strong");

matchesSelector() method

A css selector is passed in, and if the calling element matches the selector, it returns true. Many browsers have not yet supported the matchesSelector() method, and each browser implements different methods. Write wrapping functions if you want to use them.

function matchesSelector(element,selector){
    if(element.matchesSelector){
        return element.matchesSelctor(selector);
    }else if(element.msMatchesSelector){
        return element.msMatchesSelector(selector);
    }else if(element.mozMatchesSelector){
        return element.mozMatchesSelector(selector);
    }else if(element.webkitMatchesSelector){
        return element.webkitMatchesSelector(selector);
    }else{
        throw new Error("not supported");
    }
}

Element traversal

For spaces between elements, IE9 and previous versions will not return text nodes, while other browsers will return text nodes.
To make up for this difference, the Element Traversal specification defines a new set of attributes.
childElementCount: Returns the number of child elements (excluding text nodes and comments).
First ElementChild: Points to the first child element
lastElementChild: Points to the last child element.
Previous Element Sibling: Points to the previous peer element.
nextElementSibling: Points to the latter peer element.

HTML5 Extended DOM

  1. getElementsByClassName() method: Receives a parameter, a string containing one or more class names, and returns a NodeList with all elements of the specified class.
var selected = document.getElementById("myDiv").getElementByClassName("selected");
  1. ClassList attribute: HTML5 adds a new way to manipulate class names. It can make the operation easier and safer. This classList attribute is an instance of the new collection type DOMTokenList. DOMTokenList has a length attribute and has the following methods:
    add(value): Add a given string to the list.
    contains(value): Indicates whether a given value exists in the list.
    remove(value): Delete the specified string from the list.
    toggle(value): delete if it exists and add if it does not.
<div class="bd user disabled">...</div>

div.classList.remove("disabled");
div.classList.add("current");

Browsers that support classList properties include Firefox 3.6 + and Chrome.

Focus management

HMTL5 also adds the ability to manage DOM focus.
Document. ActeElement: This attribute always refers to the currently focused element in the DOM.

var button = document.getElementById("muButton");
button.focus();
alert(document.activeElement == button);//true

document.hasFocus() method: Used to determine whether a document has gained focus.

Changes in HTML Document

HTML5 extends HTML Document.
1. readyState property: There are two possible values: load (loading the document (, complete).

if(document.readyState == "complete"){
    //Execution operation
}
  1. Compatibility mode
    To distinguish between standard or mixed patterns of pages. IE adds a property named compatMode to the document for this purpose. In standard mode, the value of document.compatMode is "CSS1Compat" and in hybrid mode is "BackCompat".

document.head refers to the elements of the document.
document.charset: The actual character set used in the document.
document.defaultCharset: The default character set of the document set by the browser.

Custom Data Properties

HTML5 specifies that non-standard attributes can be added to elements, but prefix data-.

<div id="mydiv" data-appId="12345" data-myname="nicholas"></div>

The value of the custom attribute can be accessed through the element's dataset attribute.

var appId = div.dataset.appId;
var myName = div.dataset.myname;

insert text

innerText: But firefox does not support it
textContent:firefox support

function getInnerText(element){
    return (typeof element.textContent == "string")?element.textContent:element.innerText;
}

css rules

CSSRule objects represent each rule in the stylesheet.

div.box{
    background-color:blue;
    width:100px;
    height:200px;
}
//Suppose this rule is in the first style sheet on the page.
var sheet = document.styleSheets[0];
var rules = sheet.cssRules || sheet.rules;//Get a list of rules
var rule = ruless[0];
alert(rule.selectorText);//div.box
alert(rule.style.cssText);//Complete CSS code
alert(rule.style.backgroundColor);//blue

Create rules

Insert Rule.

sheet.insertRule("body{backgournd-color:silver}",0);

However, IE8 and earlier versions do not support this approach, but another approach:

sheet.addRule("body{backgournd-color:silver}",0);

Deletion rule

deleteRule(pos): Accepts a parameter, the location of the rule to be deleted.
IE supported method removeRule().

Element size


  1. Offset.

offsetHeight: The amount of space the element occupies in the vertical direction. In pixels. Including the height of the element, the height of the horizontal scroll bar, the height of the upper border and the height of the lower border.
offsetWidth: The amount of space the element occupies horizontally.
offsetLeft: Pixel distance between the left outer border of an element and the left inner border of an element.
offsetTop: Pixel distance between the upper and outer boundaries of an element and the upper and inner boundaries of an element.
offsetParent: Reference to the containing element.
Get the left offset of the element (the upper offset is similar to the principle).

function getElementLeft(element){
    var actualLeft = element.offsetLeft;
    var current = element.offsetParent;
    while(current != null){
        acrualLeft += current.offsetLeft;
        current = current.offsetParent;
    }
    return actualLeft;
}

All these offsets are read-only, and they need to be recalculated every time they visit. So try to avoid repeated access to these attributes.
2. Customer area size
It refers to the size of the space occupied by the element content and its inner margin.
clientWidth: Element content area width plus left and right margin width.
clientHeight: Element content height plus upper and lower margin height.
3. Scroll Size
Scroll Height: The total height of element content without scroll bars.
scrollWidth: The total width of an element's content without a scroll bar.
scrollLeft: The number of pixels hidden on the left side of the content area. The scroll position of the element can be changed by setting this property.
scrollTop: The number of pixels hidden above the content area.

ergodic

The DOM2 traversal and scope module defines two types of DOM structures for sequential traversal: NodeIterator and TreeWalder.
It can perform depth-first traversal operations on DOM structures based on a given starting point. Check whether the browser supports:

var supportsTraversals = document.implementation.hasFeature("Traversal","2.0);
var supportNodeIterator= (typeof document.createNodeIterator == "function");
var supportTreeWalder = (typeof document.createTreeWalder == "function");

The document.createNodeIterator() method receives four parameters:
root: The node in the tree that you want to start the search.
whatToShow: Numeric code indicating which nodes to access.
filter: A NodeFilter object, or a function that indicates whether to accept or reject a particular node.
Entity Reference Expansion: Boolean value indicating whether to extend entity references. It doesn't work in HTML.
The whattoShow parameter is a bit mask.

NodeFilter.SHOW_ALL: Displays all types of nodes.
NodeFilter.SHOW_ELEMENT: Displays element nodes.
NodeFilter.SHOW_TEXT: Displays text nodes.
Wait.

Multiple selections can be combined using bitwise or operator.

var whatToShow = NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT;

filter parameter: You can pass in a NodeFilter object or a function.
Each NodeFilter object has only one method and acceptNode() method. This method returns NodeFilter.FILTER_ACCEPT if the given node should be accessed, and NodeFilter.FILGER_SKIP if it should not be accessed.
The function passed in is similar to the acceptNode() method.

var filter = {
    acceptNode:function(node){
        return node.tagName.toLowerCase() == "p"?NodeFilger.FILTER_ACCEPT:NodeFilter.FILTER_SKIP;
    }
};
var iterator = document.createNodeIterator(root,NodeFilter.SHOW_ELEMENT,filter,false);

NodeIterator objects have two methods, nextNode() and previousNode(). The first call to nextNode() returns the root node.

var div = document.getElementById("mydiv");
var filter = function(node){
    return node.tagName.toLowerCase() == "li"?NodeFilger.FILTER_ACCEPT:NodeFilter.FILTER_SKIP;
};
var iterator = document.createNodeIterator(root,NodeFilter.SHOW_ELEMENT,filter,false);
var node = iterator.nextNode();
while(node !== null){
    alert(node.tagName);
    node = iterator.nextNode();
}

TreeWalker

TreeWalker is a more advanced version of Node Iterator. Many methods have been added.

parentNode():
firstChild():
lastChild():
nextSibling():
previousSibling():

document.createTreeWalker(): Like the document.createNodeIterator method, it receives four parameters.

var walker = document.createTreeWalder(root,NodeFilter.SHOW_ELEMENT,filter,false);

The TreeWalker type also has a currentNode attribute. Because there is no TreeWalker type in IE, there are very few cross-browser solutions that use traversal.

Range

Subsequent supplement

Posted by Bethrezen on Thu, 21 Mar 2019 16:57:52 -0700