JavaScript Advanced Programming Notes (11)

Source: Internet
Author: User

Dom Extension

The two major extensions to the DOM are the selectors API (Selector API) and HTML5.

(i) Selector API

The core of selectors API level 1 is two methods:Queryselector () and Queryselectorall () .

In a compatible browser, they can be called through an instance of the Document and element type. Currently fully supported selectors API Level 1 browser has IE 8+, Firefox 3.5+, Safari 3.1+, Chrome and opera + +.

1.querySelector () receives a CSS selector, returns the first element that matches the pattern, and returns null if none.

When the document type is called, it is found within the scope of the documentation element, and the element type is called only within the bounds of the descendant element

            // get BODY element            var body = Document.queryselector ("body");             // get an element            with ID mydiv var mydiv = Document.queryselector ("#myDiv");             // gets the first element            of a class selected var selected = Document.queryselector (". Selected");                            // gets the first image element            of class Botton var img = document.body.querySelector ("Img.button");

2.querySelectorAll () returns the matching element, returning an instance of NodeList.

To get each element returned, you can use the item () method or the square bracket syntax.

3.matchesSelector () receives a CSS selector that returns true if the calling element matches the selector, otherwise false.

When an element reference is obtained, this method can be used to detect if it is returned by the Queryselector () and Queryselectorall () methods.

Finally, make a wrapper function to use this method.

        functionmatchesselector (element, selector) {if(element.matchesselector) {returnElement.matchesselector (selector); } Else if(Element.msmatchesselector) {//ie9+                returnElement.msmatchesselector (selector); } Else if(Element.mozmatchesselector) {//firefox3.6+                returnElement.mozmatchesselector (selector); } Else if(element.webkitmatchesselector) {returnElement.webkitmatchesselector (selector); } Else {                Throw NewError ("not supported.")); }        }

(ii) Element traversal

Element Traversal API

Childelementcount: Returns the number of child element nodes

Firstelementchild: Point to first child element

Lastelementchild: Point to last child element

Previouselementsibling: Point to previous sibling element

Nextelementsibling: Point to the next sibling element

ie9+ Firefox 3.5+ Sarafi 4+ Chrome and opera10+

(iii) HTML51. Class-related extensions

①getelementsbyclassname () : receives a parameter that contains a string of one or more classes and returns a nodelist with all the elements of the specified class.

When the document object is called to return all elements that are the same as the class name, calls on the element return only the matching elements in the descendant elements, but the NodeList object is returned, with the use of Getelementbytagname () And other DOM methods that return nodelist have the same problem.

ie9+ Firefox Sarafi 3.1+ Chrome and opera 9.5+

2.classList Properties

//Remove the "User" class//gets the class name string and splits it into an arrayvarClassName = Div.className.split (/\s+/);//find the class name to deletevarpos =-1,//returns 1 if not found, i.e. not deletedI, Len; for(I=0, len=classnames.length; i < Len; i++) {     if(Classnames[i] = = "User") Pos=i;  Break;}//Delete class nameClassname.splice (i,1);//spell the rest of the class name into a string and reset itDiv.classname = Classname.join ("");

The classlist property is an instance of the new collection type Domtokenlist.

Method: Add (value): Added

Contains (value): whether a given value exists

Remove (value): delete

Toggle (value): Delete If a given value is present, no then add

ie10+ Firefox 3.6+ Chrome

2. Focus Management

The document.activeelement property always refers to the element that the DOM currently has focus on.

Document.hasfocus () Method: Determines whether the document receives focus.

The method by which the element gets focus is page loading, user input (usually by pressing the TAB key), and calling the focus () method in code.

When the document is loaded, Document.activeelement saves the document.body element, which is null during load.

IE 4+ Firefox, Safari 4+, Chrome and opera 8+.

Changes in 3.HTMLDocument

①readystate Property

There are two values: Loading loading document complete already loaded

Used to implement an indicator that indicates that the document has been loaded.

② compatibility mode

The Compatmode property tells the developer browser which rendering mode standard mode Document.compatmode value is "Css1compat" and "Backcompat" in promiscuous mode.

③head Property

var head = document.head| | Document.getelementbytagname ("Head") [0];

4. Character Set properties

CharSet The character set that is actually used in the properties document, which defaults to "UTF-16".

The Defaultcharset property is based on the default browser and operating system settings, which should be the default character set for the current document.

5. Custom Data Properties

HTML5 specifies that non-standard attributes are prefixed with data-to provide information that is not related to rendering to the element, or to provide semantic information.

The DataSet property accesses the value of the custom property, and each Data-name-form property has an object's property, except that the property name does not have a prefix.

IE11 FIrefox 6+ Chrome

6. Inserting marks

①innerhtml Property

Returns the HTML markup for all child nodes of the calling pattern in read mode.

Creates a new DOM tree in write mode and replaces it completely with all of the original child nodes of the calling element.

Different browsers return different text formats, ie lower version, opera all the tags uppercase.

In write mode, if the value contains an HTML tag, it is converted to an element according to the browser.

  document.getElementById ("hehe"). Innerhtml= "Hello & welcome,<b>\" Reader\ "!</b>";  Alert (document.getElementById ("hehe"). InnerHTML);

Most browsers innerHTML insert <script> do not execute scripts, only IE8 and previous versions are available, but need to specify the defer property for <script> and have the <script> element located after the "scoped element".

div.innerhtml = "<input type=\" hidden\ "><script deffer>alert (' Hi ');</script>";

Most browsers support such insertions <style> elements to innerHTML, but IE8 and previous versions also have the above problem.

div.innerhtml = "<style type=\" Text/css\ ">body {background-color:red;} </script> "

Elements that do not support innerHTML are <col> <colgroup> <frameset>

②outerhtml Property

Returns the HTML tag of the element that called it and all child nodes in read mode.

Creates a new DOM subtree from the specified HTM string in write mode and uses it to completely replace the calling element.

Firefox 7 and previous versions do not support outerHTML.

③insertadjacenthtml () method

Receives two parameters: the insertion position and the inserted HTML text, the first parameter must be one of these values: Beforebegin afterbegin beforeend afterend.

IE Firefox 8+ Sarafi Opera Chrome

④ Memory and performance issues

// Each loop is set to innerHTML once, and the data is read from innerHTML  for  (var i=0,len=values.length;i<len;i++) {     + = "<li>" + value[i] + "</li>";} // build the string separately, var itemhtml = "";  for  (var i=0,len=values.length;i<len;i++) {      + = "<li>" + value[i] + "</li>"  ;}       = itemshtml;

7.scollIntoview () method

By scrolling the browser window or a container element, the calling element can appear in the viewport. If you pass in true or do not pass in parameters, the window scrolls so that the top of the calling element is as flush as possible to the top of the viewport. The incoming false call element appears as full as possible in the viewport.

(iv) Proprietary extensions 1. Document mode

Documentmode

2.children Properties

Contains only the elements of the same or element child nodes, and ChildNodes is no different.

IE5 Firefox 3.5 Safari 3 OPERA8,IE9 returns only ELEMENT nodes

3.containss () method

The element that is called is an ancestor node that receives a parameter: a descendant node. Returns true if the detected node is a descendant node.

IE Firefox + Sarafi Opera Chrome

        //General-purpose containers functions        functioncontains (Refnode, Othernode) {if(typeofRefnode.contains = = "function" &&                     (!client.engine.webkit | | Client.engine.webkit >= 522)){                returnRefnode.contains (Othernode); } Else if(typeofRefnode.comparedocumentposition = = "function"){                return!! (Refnode.comparedocumentposition (othernode) & 16); } Else {                varnode =Othernode.parentnode;  Do {                    if(node = = =Refnode) {                        return true; } Else{node=Node.parentnode; }                }  while(Node!==NULL); return false; }        }

4. Inserting text

①innertext Property

Reading a value installs all the text of the subdocument tree in the order in which they are installed.

When the value is written, all child nodes are deleted, and the text nodes that contain the corresponding text values are inserted,

Set innertext equal to InnerText to remove all HTML tags.

ie4+ sarafi3+ Opera 8+ Chrome

InnerText ignores the inline style and script, and Textcontent returns the style and script code in the row like any other text.

②outertext Property

5. Scrolling

scollintoviewifneeded

Scollbylines

Scollbypages

JavaScript Advanced Programming Notes (11)

Related Article

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.