1. Selector API

When manipulating nodes or elements, we need to select the node we want to operate on. Here we need to use the selection tool —- selector API

At the heart of the Selectors API Level 1 are two methods: querySelector() and querySelectorAll().

1.1. QuerySelector () method

It receives a selector and returns the first element that meets the requirement, or null if not

Var div01 = document.querySelector("div"); Var element123 = document.querySelector("#123"); Person = document.querySelector(".person "); Var PersonImg = document.querySelector("img.Person");Copy the code

Calls to document will look for matches in the scope of the document, while calls to Element will only look for matches in the descendants of the element

1.2. QuerySelectorAll () method

The input, like the previous one, returns an entire instance of NodeList, that is, a whole set of the API’s callable types, besides Document, Element, and documentFragment

Var emmms = document.getelementById (".123").querySelectorAll("emmm");Copy the code

To get each element of the returned NodeList, use the item() method, or square bracket syntax (array imitation).

// Strongs is an element of all var I, len, strong; for (i = 0, len = strong.length; i < len; i++ ) { strong = strongs[i]; / / or strongs. Item (I); strong.className = "important"; }Copy the code

1.3. MatchesSelector () method

The Selectors API Level 2 specification adds a method for the Element type, matchesSelector(). Return true if the calling element matches the input selector, false if not

/ / check whether the body element of the calling element to match the if pagel (document. Body. MatchsSelector (" body. Pagel ")) {/ / true}Copy the code

2. Element traversal

Spaces between elements did not return text nodes in versions prior to IE9, whereas all other browsers do, resulting in differences that can lead to inconsistent behavior when using attributes such as firstNode

So the Element Traversal API adds the following five attributes to the DOM Element.

  1. ChildElementCount: Returns the number of child elements (excluding text nodes and comments).
  2. FirstElementChild: Points to the first child element; Element version of firstChild.
  3. LastElementChild: points to the last child element; Element version of lastChild.
  4. PreviousElementSibling: Refers to the previous sibling element; Element version of previousSibling.
  5. NextElementSibling: Points to the next sibling element; The elemental version of nextSibling.

You can more easily traverse elements

var i, len, child = element.firstElementChild; wheil(child ! = element.lastelementChild) {// This is a shorthand representation of some operations on child, such as writing an output here instead of a method processChild(child); child = child.nextElementSibling; }Copy the code

3. HTML5

Its rules define a large number of JS apis

3.1. Class-related extensions

3.1.1. GetElementsByClassName () method

You can more easily add event handlers to elements with certain classes

Takes a parameter, which can be a string containing one or more class names, and returns a NodeList with all elements of the specified class, regardless of class name order

Var element01 = document.getelementsbyId ("123").getelementsbyclassName ("456"); / / get all the classes contained in the 789 and 012 all the elements of the var element02 = document. The getElementsByClassName (" 789 012 ");Copy the code

The scope of the call varies depending on the scope of the search. A call to document will return the class name matching all elements, while a call to an element will only look up descendants of that element

3.1.2. ClassList attributes

Simplifies adding, modifying, and deleting className attributes

The classList attribute is an instance of DOMTokenList, which has a length attribute, and each element can be retrieved using either the item() method or square bracket syntax.

  1. Add (value) : Adds the given string value to the list. If the value already exists, it is not added.

  2. Contains (value) : indicates whether a given value exists in the list, and returns true if it does, false otherwise.

  3. Remove (value) : Removes the given string from the list.

  4. Toggle (value) : If a given value already exists in the list, remove it; If there is no given value in the list, add it.

    <div class = "zy ZJJ user">... </div>; Remove ("user"); // Delete the user class div.classlist. remove("user"); // Add the qwer class div.classlist. add("qwer"); Div. Classlist. toggle("user"); If (div. ClassList. Contains ("zzy")) {// Perform an action}Copy the code

3.2. Focus management

  1. The Document.ActiveElement property, which always refers to the element in the DOM that is currently in focus. When the document has just finished loading, a reference to the Document. activeElement is stored in the document. The value of Document.ActiveElement is null during document loading.

Elements get focus by page loading, user input (usually by pressing Tab), and by calling the focus() method in your code.

var button = document.getElementById("myButton"); Button.focus (); //true document.activeElement === button;Copy the code
  1. The document.hasfocus () method, which is used to determine whether the document is in focus. It can also be used to determine whether the user is interacting with the page

The combination of these two elements tells you exactly which element the user is interacting with

3.3. Changes of HTMLDocument

3.3.1. ReadyState attribute

This property has two possible values:

  1. Loading, loading a document;
  2. Complete, the document has been loaded.

We can use document.readyState to implement indicators to see if the document has finished loading

If (document.readyState == "complete") {// Execute operation}Copy the code

3.3.2. Compatibility mode

For standard mode, document.compatMode is equal to “CSS1Compat”, whereas for promiscuous mode, The value of document.compatMode is equal to “BackCompat”.

3.3.3. Head properties

3.4. Character set properties

  1. The charset property, whose value is “UTF-16”, represents the actual character set used in the document

  2. If the default character set is not used, the value of charset and defaultCharset may be different

You can obtain specific information about the character encoding used in the document through these two attributes, which can ensure that users can normally view the page or use the application

3.5. Customize data attributes

In H5, you can add non-standard attributes for elements by yourself, and prefix data-. You can easily know which part of the page you click from according to the performance of user-defined data attributes

The data- prefix is not required for calls other than the first use (similar to defining a custom property)

3.6. Insert tags

It is easier to insert HTML strings directly in the case of large-scale manipulation of nodes

3.6.1. InnerHTML property

In read mode, it returns HTML tags corresponding to all children of the calling element

In write mode, a new DOM tree is created based on the specified value, replacing all the original child nodes of the element

3.6.2. OuterHTML property

3.6.3. The insertAdjacentHTML() method

3.6.4 radar echoes captured. Memory and performance issues

3.7 scrollIntoView () method

Resolving scrolling pages

Can be called on all HTML elements

Passing true or not, the window scrolls so that the top of the calling element is as flush as possible with the top of the viewport.

If false is passed in, the calling elements appear as fully as possible in the viewport, not necessarily flush

4. Proprietary extensions

An extension that is exclusive to some browsers and is not standard

4.1. Document mode

The document schema determines which level of CSS we can use, which apis we can use in JS, and how we treat document types. Each version of IE5,7,8, and 9 has its own document schema

For example, IE5 renders pages in promiscuous mode, and IE7 is IE7 standard mode. They can’t use the new features after IE8

IE8 is IE8 standard mode, so you can use the Selectors API, more CSS2-level Selectors and some CSS3 features, as well as some HTML5 features. Again, new features are unavailable after IE9

Document mode in IE9 is the highest document mode

If you want to force the browser to render a page in a certain mode, you can use the equivalent tag or use the HTTP header x-UA-compatible

<meta http-equiv=" x-UA-compatible "content="IE=EmulateIE7">Copy the code
  • Edge: Always render the page in the latest document mode. Ignore the document type declaration. For IE8, always render the page in IE8 standard mode. For IE9, pages are rendered in IE9 standard mode.
  • EmulateIE9: Render the page in IE9 standard mode if there is a document type declaration, otherwise set document mode to IE5.
  • EmulateIE8: Render the page in IE8 standard mode if there is a document type declaration, otherwise set document mode to IE5.
  • EmulateIE7: Render the page in IE7 standard mode if there is a document type declaration, otherwise set document mode to IE5.
  • 9: Forces pages to be rendered in IE9 standard mode, ignoring document type declarations.
  • 8: Forces pages to be rendered in IE8 standard mode, ignoring document type declarations.
  • 7: Force pages to be rendered in IE7 standard mode, ignoring document type declarations.
  • 5: Force the document mode to be set to IE5, ignoring the document type declaration.

By default, browsers use document type declarations to determine document schemas

The document.documentMode property tells you what document mode is used for a given page

4.2 children attribute

The reason for this attribute is that previous versions of IE9 differed from other browsers in the way they rendered whitespace in text nodes

This property is an instance of HTMLCollection and contains only the children nodes of an element that are also elements. Otherwise, children and childNodes are the same

Var childCount = element.children.length; var firstChild = element.children[0];Copy the code

4.3. The contains () method

Used to find out whether a node is a descendant of another node

You can obtain this information without going through the DOM document tree

Apply the ancestor node to call this method, returning true and false

/ / test the < body > element is the offspring of the < HTML > element alert (document. DocumentElement. The contains (document. The body)); //trueCopy the code
DOM Level 3 compareDocumentPosition()

Used to determine the relationship between two nodes

Returns a bitmask representing the relationship

mask Relationship between nodes
1 Irrelevant (the given node is not in the current document)
2 Precede (the given node precedes the reference node in the DOM tree)
4 Last (the given node comes after the reference node in the DOM tree)
8 Contains (the given node is the ancestor of the reference node)
16 Included (the given node is a descendant of the reference node)

We can convert the resulting mask into a Boolean value using the logic to detect node relationships with the function

4.4. Insert text

1. The innerText attribute

You can manipulate all text content contained within the element, including text in the document tree

He would concatenate all the text in the tree in order from shallow to deep

Writing a value through innerText removes all of the element’s child nodes and then inserts a text node containing the corresponding text value

div.innerText = " Hello \" world \" !" // When you set the innerText property, you also encode HTML syntax characters (less-than, greater-than, quotes, and ampersand) that exist in the text.Copy the code

Because innerTest always generates only one child text node of the current node, it must delete the other child tags in order to generate only one child text node. We can use this to filter out HTML tags

div.innerText = div.innerText;
Copy the code
Similar method :DOM Level 3 textContent property

The two properties do not return exactly the same content

This will return inline styles and scripts

2. OuterText properties

The difference with innerText is that the scope extends beyond the node that calls it

Read the text just like that

But in write mode the outerText replaces the entire element, including its children.

div.outerText = " Hello world "; // This is equivalent to assigning hello~ to a new variable and replacing the element with the new variable. The element is removed and cannot be accessedCopy the code

Rolling 4.5.

  • ScrollIntoViewIfNeeded (alignCenter) : Scrolls the browser window or container element to make it visible when the current element is not visible in the viewport. This method does nothing if the current element is visible in the viewport. If the optional alignCenter parameter is set to true, the element is displayed in the middle of the viewport as far as possible (vertically).

  • ScrollByLines (lineCount) : Scrolls the contents of an element to a specified line height. The lineCount value can be positive or negative.

  • ScrollByPages (pageCount) : Scrolls the content of an element to the specified height of the page, which is determined by the height of the element.

    // Let the current element enter the browser viewport when it is not visible document.images[0].scrollinToViewIfneeded ();

    / / main rolling line 5 document. The page body. ScrollByLines (5);

    / / the page theme rolling back 2 page document. The body. The scrollByPages (2);