Home >Web Front-end >JS Tutorial >DOM expansion of JS advanced programs

DOM expansion of JS advanced programs

小云云
小云云Original
2018-03-07 13:30:131536browse

11.1 Selector API:

The two core methods of SelectorsAPI are: querySelector() and querySlelctorAll(). In compatible browsers, they can be called through instances of Domcument and Element types.

11.1.1 querySelector() method:

The querySelector() method receives a css selector and returns the first element that matches the selector. If there is no match, it returns null.

Calling the querySelector() method through document will find matching elements within the range of document elements.

Elementquery calls the querySelector() method only to find matching elements in the descendant elements of the element

11.1.2querySelectorAll()

var body=document.querySelector("body");
var p=body.querySelector(".menu_1")
//    var li=p.querySelector("li");
var li=p.querySelectorAll("li");
for(var i=0;i<li.length;i++){
var list={};
list[i]=li[i].innerHTML;
alert(list[i]);
    }

11.1.3matchesSelector

This method receives a parameter, which is the css selector, and returns true if the called method matches the element.

11.2 Element Traversal

Elment Traversal API adds the following 5 attributes to DOM elements.

1: childElementCount: returns the number of child elements

2: firstElementChild: points to the first child element, firstChild element version;

3: lastElementChild: points to the last one Child element, lastChild element version;

4: previousElementSibling: points to the previous sibling element;

5: nextElementSibling: points to the next sibling element;

11.3HTML5

11.3.1 Class-related extensions

1: getElementByClassName() This method receives a parameter, a string of one or more class names, and returns a NodeList with all specified elements.

2: classList attribute: (for class="Operation here")

The classList attribute is an instance of the new collection type DOMTokenList. Similar to other DOM collections. Has the following methods:

add(value): Adds the given string to the list.

contains(value): Indicates whether the given value exists in the list. If so, it will return true. If not, it will return false.

remove(value) Removes the given string from the list

toggle (If the given value exists in the list, delete it, if there is no given value, add it.)

e9132549569fb02f168a4ec8b3ac532894b3e26ee717c64999d7867364b1b4a3
3f1c4e4b6b16bbbd69b2ee476dc4f83a
var elem = document.getElementById("select");
var classNum =elem.classList;
console.log(classNum);
2cacc6d41bbb37262a98f745aa00fbf0

At this point, you can use the above method to manipulate the parameters inside.

11.3.2 Focus Management

HTML5 also adds the function of auxiliary management of DOM. The first is the document.activeElement property, which always refers to the currently focused element of the DOM. Gets the element that the current user has focus on.

use. focus() method

11.3.3 Changes in HTMLDocument

1: readyState attribute

This attribute has two values

1; loading, loading Document

2: complete, the document has been loaded.

The most appropriate way to use the document.readyState property is to use it to implement an indicator that the document has been loaded. Indicates that the document has been loaded.

if(document.readyState=="complete"){
       //执行操作
}

2: Compatibility mode:

Since IE6 began to distinguish whether the mode of rendering the page is standard or mixed, IE added an attribute called compatMode to the document to tell developers The page uses that rendering mode.

There are two return values: CSS1compat, and BackComapat.

corresponds to standard mode and mixed mode respectively.

3: head attribute

If it cannot be used through document.head, use document.getElementByTagName();

11.3.4 Character set attribute

By document .charSet=""; to modify the encoding format of the page;

11.3.6 Insert tag

1: innerHTML attribute

In read mode, the innerHTML attribute returns the calling element's HTML tags corresponding to all child nodes. In write mode, innerHTML will create a new DOM tree based on the specified value.

You can use this attribute to add tags to the specified tag, but not all tags are supported

2: outerHTML attribute

In read mode, outerHTML Returns the HTML tag of the calling element and all its child nodes. In write mode, outerHTML will create a new DOM tree based on the specified HTML characters, and then completely replace the calling element with this DOM subtree.

var val = elem.outerHTML;

Read mode: Return all HTML tags

Write mode: Replace the corresponding DOM elements.

<p id="select" class="aa ss dd ff hh ">
<p>this is a test Demo</p>
</p>
elem.outerHTML="<p>这是一个测试的demo</p>"

3: insertAdjeacentHTML() method

The last method to insert markup.

Receives two parameters: the insertion position and the HTML text to be inserted. The first element must be one of the following values.

1: beforebegin, insert an adjacent sibling element before the current element.

2: afterbegin, insert a new child element below the current element or insert a new element before the first element

3: beforeend, insert a new element below the current element child element or insert a new element after the last element

4: afterend, add an adjacent sibling element after the element.

4: Memory and performance issues;

Using the method introduced in this section to replace child nodes may cause memory problems in the browser, but using the innerHTML attribute will still bring us a lot of traversal , the reason is that when setting innerHTML or outerHTML, an HTML parser will be created. This parser runs on the basis of browser-level code, so it is much faster than js.

11.3.7scrollIntoView method

Scroll

11.4.1Document mode:

Document mode determines which level of css you can use and which APIs can be used in js:

There are four document modes in total:

IE5: Render the page in mixed mode, The new features in IE8 and higher versions cannot be used

IE7: Render the page in IE7 standards mode, and the new features in IE8 and higher versions cannot be used

IE8: Render the page in IE8 standards Modal rendering, new features in IE8 are all available, so you can use the SelectorsAPI, more CSS2 level selectors and some CSS3 features. There are also some HTML5 features

IE9 - IE9 standards mode rendering page. All new features are available. For example, the function of EMACSript5.

11.4.2 children attribute

There is almost no difference between the children attribute and childNodes. They are both used to return all child nodes.

11.4.3contain (contain) method:

is used to determine whether the node is a descendant node of a certain node. You can directly understand the literal meaning in English, including.

Parent node.contain (a certain node): If true is returned, it is included, otherwise false is returned.

You can also use compareDocumentPosition() to compare file positions, which will return some masks to determine the position relationship

In order to imitate the contain() method, you should pay attention to returning 16;

11.4.4 Insert text:

1: The innerText attribute

will operate on all the values ​​​​in the element and splice the documents together from shallow to deep. The difference between

and innerHTML is: innerHTML will display all element tags, but innerText will only return the spliced ​​string

When writing, only one text child node will be displayed.

2: outerText attribute

There is basically no big difference between outerText and innerText except that the scope is expanded to include its nodes. The results are exactly the same when reading text, but completely different when writing. outerText will not only replace the child elements of the element that calls it, but will replace the entire element. It is recommended not to use it.

11.4.5 Scroll:

1: scrollIntoviewIfNeeded(alignCenter): Only scroll the browser if the element is not visible in the viewport.

2: scrollByLines(lineCount): Scroll the content of the element to the specified page height. lineCount can be a positive or negative value.

3: scrollBypage(pageCount): Scroll the content of the element to the specified page height. The specific height is determined by the height of the element.

Note: scrollIntoView() and scrollIntoviewIfNeeded(alignCenter) work on the element container, while scrollByLines(lineCount) and scrollBypage(pageCount) work on the element itself.

Chapter 12: DOM2 and DOM3

12.1.1 Changes for XML namespaces

With XML namespaces, elements of different XML documents can be mixed together , don't worry about naming conflicts, technically speaking, HTML does not support XML namespaces, but XHTML supports XML namespaces.

1: Changes in Node type

In DOM2 level, the Node type contains the following namespace-specific attributes.

localName: Node name without namespace prefix.

namespaceURL: The namespace URL is null.

prefix: namespace prefix or null.

2: Changes in document type

The Document type in DOM2 level has also changed, including the following namespace-related methods.

createElementNs(namespaceURI,tagName): Create a new element belonging to the namespace namespaceURI using the given tagName.

createAttributeNS(nameSpaceURI, attributeName) Creates a new attribute belonging to the namespace nameSpaceURI using the given attributeName.

getElementByTagNameNs(namespaceURI, tagName) returns a NodeList of tagName elements belonging to the namespace URI.

3: Changes in Element type

Changes related to Element in "DOM2 level" mainly involve operating characteristics. The new method is as follows.

getAttributeNS(namespaceURI, localName) Gets the attribute of the namespace URI named localName

getAttributeNodeNS(namespaceURI, localName) Gets the attribute node belonging to the namespace URI and named localName

getElementsByTagNameNS(namespaceURI, tagName) returns the nodeList belonging to the namespace namespaceURI

hasAttributeNS(namespaceURI, localName) determines that the current element is an attribute named localNaem, and the namespace of the attribute is namespaceURI

removeAttributeNS (namespaceURI, localName) deletes the attribute that belongs to the namespace URI and is named localName

setAttributeNS (namespaceURI, qualifiedName, value): Sets the attribute value that belongs to the namespace URI and is named qualifiedName to value

setAttributeNodeNS (attNode) sets the attribute node belonging to the namespace namespaceURI

4: Changes in NamedNodeMap type

Since attributes are represented by NamedNodeMap, these methods are only for Feature usage

1: getNamedItemNS(namespaceURI, localName): Get the item that belongs to the namespace namespaceURI and is named localName

2: removeNamedItemNS(namespaceURI, localName): Remove the item that belongs to the namespace namespaceURI and is named localName Item named localName

3: setNamedItemNS(node): Add node, which has namespace information specified in advance.

Since properties are generally accessed through elements, these methods are rarely used.

12.1.2 Other changes

1: Changes in documentType type

Added three attributes: publicID systemId and internalSubset.

2: Changes in document type:

The DOM2 core is still document. The implementation object specifies two new methods: creatDocumentType() and creatDocument()

The former is used to create a new DocumentType node and accepts three parameters: document type, publicID, systemID;

When creating a new document, you need to use the createDocument() method, which also accepts three parameters: namesp-aceURI, tag name of the document element, and new document type

3: Changes in Node type

Just add the isSupported() method: used to determine what capabilities the current node has.

This method receives two parameters, feature name and feature version number.

12.2 Style

There are three ways to define styles in HTML: external 2cdf5bf648cf2f33323966d7f58a7f3f, embedded c9ccee2e6ea535a969eb3f532ad9fe89, and using the style attribute to modify it in the element tag.

12.2.1 The style of the access element


# CSS attributes javascript attributes


# Background-Image style.backgroundimage

COLOR Style. color

display                                                            style.display

font-family                                               style.fontFamily


1: DOM style properties and methods:

"DOM2-level style "The specification also defines some properties and methods for the style object. These properties and methods can also modify the style while providing the style properties of the element. These properties and methods are listed below.

cssText: You can access the CSS code in the style.

length: The number of CSS properties applied to your element.

parentRule: CSSRule object representing CSS information

getPropertyCssValue(propertyName): Returns a CssVal object containing the given property value.

getPropertyPriority(propertyName): If the property is given! important setting, then return! important, otherwise an empty string is returned

getPropertyValue() returns the string value of the given property

item() returns the name of the CSS property at the given position

removeProperty (propertyName): Removes the given style from the style

setProperty() sets the given property to the corresponding value, plus the priority permission flag.

In actual development, getPropertyValue() is used more frequently

2 Computed style

getComputedStyle() method. This method needs to accept two parameters: the element to get the calculated style and a pseudo-element string. If you do not need a pseudo element string, you can fill in null.

Example: Get element style

12.2.2 Operating style sheet

CSSStyleSheet inherits from StyleSheet, which can be used as an interface to define non-CSS Style sheet. The properties inherited from the StyleSheet interface are as follows.

disable: Boolean value indicating whether the style sheet is disabled

href: If the style change is included through 2cdf5bf648cf2f33323966d7f58a7f3f, it is the URL of the style sheet: otherwise, it is null

media: A collection of all media types supported by the current style sheet

ownerNode: A pointer to the node that owns the current style sheet

parentStyleSheet: A pointer to the imported style sheet

title: The value of the title attribute in ownerNode.

type: A string representing the style sheet type

cssRules A collection of rules in the style sheet

ownerRule: If the style sheet is imported through @import, this attribute is a Pointer, pointing to the imported rule, otherwise, the value is null

deleteRule(index): Delete the specified rule

insertRule: (Method) Insert the rule string into the cssRule collection

All styles applied to the document are represented through the document.stylesheets collection

1: CSS rules:

The CSSStyleSheet object contains the following objects:

cssText: Returns the text corresponding to the entire rule.

parentRule: If the current rule is an import rule, this property returns the import rule; otherwise it is null

parentStyleSheet: The style sheet to which the current rule belongs

SelectorText: Returns the current rule The selector text.

Style: A CSSStyleDeclaration object, through which you can set and get the style sheet of a specific style in the rule.

type: A constant value representing the rule type.

The most commonly used properties are cssText, selectorText and Style.

2: Create rules

DOM regulations. To add a new rule to the now styled table, you need to use the insertRule() method. This method accepts two parameters: rule text and inserted index

Example:

sheet.insertRule("body{background-color:silver}",0);//DOM method.

To insert rules across browsers, you can use the following function. This function accepts four values: the stylesheet to which the rule is to be added and the same three parameters as addRule(), as shown in the figure:

3. Delete the rule:

from the stylesheet The method to delete a rule is deleteRule()

1: offset

The visible size of the element is determined by its height and width, including all padding and scroll bar border size (note , excluding outer borders). The offset of the element can be obtained through the following four properties.

offsetHeight: The size of the space occupied by the element in the vertical direction, measured in one pixel;

offsetWidth: The size of the space occupied by the element in the horizontal direction, measured in pixels.

offsetLeft: The pixel distance between the left border of the element and the inner left border of the containing element.

offsetTop: The distance between the outer border of the element and the inner border of the element.

The offsetLeft and offsetTop attributes are related to the containing element, and the reference of the containing element exists in the offsetParent attribute

2: The size of the client area:

The box model is divided into margins ( margin) inner margin (padding) border (border) and content (contain) area

The client area is similar to the contain area of ​​the box model. It has two properties, clienWidth and clienHeight

3 :Scroll size:

Scroll size refers to the size of the element containing scrolling content

Contains four values:

scrollHeight: In the absence of scroll bars, The total height of the element content

scrollWidth: The total width of the element content without scroll bars

scrollLeft: The number of pixels hidden on the left side of the content area

scrollTop: The number of pixels that are shadowed above the content area

scrollHeight and scrollWidth are only used to determine the actual size of the element content.

The scrollLeft and scrollRgiht attributes can be used to determine the current scrolling state and set the scrolling position of the element.

4: Determine the size of the element

Each browser provides a getBoundingClientRect() method for each element. This method returns a rectangular object containing four attributes: left, top, right , and bottom

12.3 Traversal

DOM2-level traversal and range modules define two types to assist in completing sequential traversal of the DOM structure: NodeIterator and TreeWalker.

12.3.1 NodeIterator

The NodeIterator type is the simpler of the two, and new instances of it can be created using the document.creatNodeIterator() method. This method receives four parameters

root: the node in the tree that you want to use as the starting point for the search.

whatToshow: Numeric code indicating which nodes to visit.

filter: is a NodeFilter object

entityReferenceExpansion: Boolean value, indicating whether to extend the entity reference.

DOM2-level traversal and range

(1) Traversal is to use NodeIterator or TreeWalker to perform depth-first traversal of DOM

(2) NodeIterator is a simple interface that only Allows moving back and forth in steps of one node. While TreeWalker provides the same functionality, it also supports movement in all directions of the DOM structure, including parent nodes, sibling nodes, and child nodes.

(3) Scope is a means of selecting a specific part of the DOM structure and then performing the corresponding operation.

(4) Use range selection to delete certain parts of the document while keeping the document structure in good format, or to copy the corresponding parts of the document.

(5) IE8 and earlier versions do not support the "DOM2 level traversal and range" module, but it provides a proprietary text range object that can be used to complete simple text-based operation ranges. IE9 fully supports DOM traversal

Chapter 17: Error handling and debugging:
17.1.1 IE

IE是唯一一个在浏览器界面窗体中显示JS错误的,发生JS错误时,浏览器左下角会出现一个黄色的图标,旁边显示着Error on page

17.2.1try-catch语句:

try{
    //可能出错的语句
}catch(error){
    //怎么处理 
}

1:finally子句

finally在try语句中一定会被执行,不管catch语句是否已经执行,他会忽略catch语句。

2:错误类型:

Error

EvalError

RangeError

ReferenceError

SyntaxError

相关推荐:

细说JavaScript对dom的操作

Vue中DOM的异步更新策略以及nextTick机制详解

jQuery中DOM节点操作方法总结

The above is the detailed content of DOM expansion of JS advanced programs. For more information, please follow other related articles on the PHP Chinese website!

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