JS Learning (DOM extension)

Source: Internet
Author: User
Tags custom name

Selector API

The main purpose of this API is to let JS native support CSS queries.

Queryselector ()

This method receives a CSS selector that returns the first element that matches the pattern or null.

vardocument.querySelector("body");
Queryselectorall ()

This method also receives a CSS selector that returns all the matching elements in a static nodelist form.

var strongs = document.querySelectorAll("p strong");strong = strongs[i];strong = strongs.item(i);
Matchesselector ()

Receives a CSS selector and returns whether the calling element matches the selector.

if (document.body.matchesSelector("body.page1")){    //true}
ELEMENT traversal

Because of the problem with the blank text type node, the childnodes contains an empty literal node. This leads to a very inconvenient traversal of elements. So with these properties, they all return only the true elements:

    • Childelementcount
    • Firstelementchild
    • Lastelementchild
    • Previouselementsibling
    • Nextelementsibling

This way the elements are traversed without having to determine the node type:

var i,     len,    child = element.firstElementChild;while(child != element.lastElementChild){    processChild(child);         child = child.nextElementSibling;}
HTML5 Extensions related to classes

Getelementsbyclassname ()
Receives one or more class names, returning a dynamic nodelist.

var selected = document.getElementById("myDiv").getElementsByClassName("username current");

classlist
This is easy to add, delete the class name, the previous use of the ClassName property is a string, each time to change to find the one to be changed, delete or change, and then spell out the new string. It's much easier with this property.
Classlist is an instance of the new type domtokenlist. 4 methods are available:

    • Add (Value)
    • Contains (value)
    • Remove (value)
    • Toggle (value) is deleted if it exists, does not exist to add
div.classList.add("current");div.classList.toggle("user");div.classList.remove("user");if (div.classList.contains("bd")) {}
Focus Management

Added the Document.activeelement property, which always references the element in the DOM that currently has the focus. By default, when a document has just been loaded, it holds the body element, which is null during loading.
Added the Document.hasfocus () method to determine whether the element has the focus.

vardocument.getElementById("myButton");button.focus();alert(document.activeElement === button);   //truealert(document.hasFocus());  //true
Changes in HTMLDocument

ReadyState Property
Indicates whether the document is loaded and has two possible values: loading and complete.

if (document"complete"){    }

compatibility Mode
The patterns that differentiate between rendered pages are standard or mixed. The property is Document.compatmode. The standard mode value is Css1compat and promiscuous mode is Backcompat.

if (document"CSS1Compat"){    alert("Standards mode"else {    alert("Quirks mode");}

Head Property
The document.head can be accessed directly as a body.

vardocumentdocument.getElementsByTagName("head")[0];
Character Set properties

HTML5 has added several properties related to the document character set
CharSet represents the character set that is actually used in the document, which is UTF-16 by default and can be

<meta charset="UTF-8">

To set, or respond to the head, or directly set this property in JS.

alert(document.charset);alert(document.defaultCharset);

Another property is Defaultcharset, which represents what the character set should be based on the default browser settings.

Custom Data Properties

Using data-plus a custom name, you can define your own node attributes, using a dataset access in JS, the value of this property is an instance of a domstringmap, which is a mapping of a key-value pair. Do not use data-prefixes when accessing.

var div = document. getElementById("Mydiv");var appId = div. DataSet. AppId;var myName = div. DataSet. MyName;Div. DataSet. AppId=23456;Div. DataSet. MyName="Michael";Alert (Div. DataSet. MyName);Alert (Div. DataSet. AppId);Even if the original is not written in the DOM can also be set, will be synchronized to the DOM Div. DataSet. Haha="hahaha";Alert (Div. DataSet. Haha);
Insert Marker

Using the Insert tag, you can directly insert an HTML string to build the DOM tree.
InnerHTML
In read mode, returns a string of HTML tags corresponding to all child nodes of the calling element.
In write mode, a new DOM tree is created based on the specified value, and then all child nodes of the calling element are replaced.

alert(document.body.innerHTML);var div = document.getElementById("myDiv");div.innerHTML"<p>balalala</p><button>balalala</button>";

Although most browsers do not support adding a script node in innerHTML, IE8 is supported, though somewhat special, to be inserted after a scoped element. It is also possible to insert executable code through events such as onclick. Therefore, in order to be safe, we must pay attention to safety when using innerHTML.
The style element is supported. There are some special in IE8, to be inserted after the element with scope.

The style element is supported. There are some special in IE8, to be inserted after the element with scope. Failed div.innerhtml = "<style type=\ "Text/css\" > body {background-color: red; }</style>";//Success div.innerhtml =" _<style type=\ "Text/css\" > body {background-color: red; }</style>";//Success div.innerhtml ="<input type=\ "hidden\"><style type=\ "Text/css\" > body {background-color: red; }</style>";

outerhtml
This is not just the substitution of child elements, but the invocation element itself is also replaced.
insertadjacenthtml ()
This method inserts the HTML text at the specified location, which can be specified in 4 locations:

    • Before begin: Inserts a sibling element before the current element
    • After begin: Inserts all child elements of the current element, as child elements of the current element
    • BeforeEnd: Inserted after all child elements of the current element, as child elements of the current element
    • Afterend: Inserts a sibling element after the current element
element.insertAdjacentHTML("afterend""<p>Hello world!</p>");

memory and performance issues
When you replace a node with these several methods, the node may still be in memory if it has an event handler or references other objects as attributes. So it's a good idea to manually delete these.
However, when inserting a new element, this method is much more efficient in writing or executing than we do with DOM operations, and an HTML parser is created when the method is executed, which is typically a browser-level C + + code.
However, creating and destroying HTML parsers is a cost, so try to reduce the number of calls and make the string a single call at a time.

scrollIntoView ()

Div.scrollintoview ();
This is to let the screen scroll to where this element is located so that everyone can see. Pass in true to try to flush the top of the element with the screen, passing false to display as many elements as possible.
This effect can also be achieved by setting the current element to focus.

Proprietary outreach

These are all browser implementations, some are common, and some are not universal.

Document mode

Determines what functions can be used, IE5,IE7,IE9, etc.
You can force the browser to render in what way, via the HTTP header's x-ua-compatible or meta tag.

<meta http-equiv="X-UA-Compatible" content="IE=IEVersion">

The ieversion can be edge, EmulateIE9, EmulateIE8, EmulateIE7, 9, 8, 7, 5.
JS can also be obtained, ie in the seemingly.

vardocument.documentMode;
Children Property

Only return element child nodes, no messy text nodes

var childCount = element.children.length;
Contains () method

One node is not another descendant

alert(document.documentElement.contains(document.body)); //true
Insert text

InnerText

<div id="Content">    <p>This is a<strong>Paragraph</Strong>With a list following it.</P>    <ul>        <li>Item 1</li>        <li>Item 2</li>        <li>Item 3</li>    </ul> </div>

Use innertext Read for content:

isparagraphwithlistit123

All child nodes are overwritten and HTML-encoded HTML tags are removed to avoid generating multiple nodes. This can be used to filter user input OH.
Some browsers do not support this, but support textcontent.

function getInnerText(element){    return (typeof"string") ?        element.textContent : element.innerText;}function setInnerText(element, text){    if (typeof"string"){        element.textContent = text;    else {        element.innerText = text;    }}

outertext
Read as innertext, overwriting the calling node when writing.

JS Learning (DOM extension)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.