JavaScript Advanced Programming DOM Extensions

Source: Internet
Author: User

  Although DOM has developed a series of APIs for XML and HTML document interaction, there are still several specifications that extend the standard DOM. Many of these extensions are browser-specific, but later become a fact standard, so other browsers provide the same implementation, and browser developers will still add proprietary extensions directly to the DOM to compensate for deficiencies when they discover that a feature is missing. These standard extensions and proprietary extensions are described below.

One, the selector API

The function of the selector API is to select a DOM element that matches a pattern based on the CSS selector. The core of jquery is querying DOM documents with CSS selectors to get references to elements, thus getElementById () and getElementsByTagName () are thrown away. The selector API is a standard launched by the web to allow browsers to support native support for CSS queries. Its core approach is Queryselector (), Queryselectorall () and Matchesselector ().

Queryselector () accepts a CSS selector that returns the first character that matches the pattern.

    //Get BODY element    varBODY = Document.queryselector ("Body"); //get an element with id "mydiv"    varMydiv = Document.queryselector ("#myDiv"); //gets the first element of the class named "Selected"    varSelected = Document.queryselector (". Selected"); //gets the first image element with the class name "button"    varimg = Document.queryselector ("Img.button");

  Queryselectorall () returns all matching elements, not just an element, that is, an instance of nodelist.

// get all the <em> elements in the div var ems = document.getElementById ("mydiv"). Queryselectorall ("em"); // get all elements of class selected var selectors = Document.queryselectorall (". Selected"); // get all <strong> elements in the <p> element var strongs = Document.queryselectorall ("P Strong");

  Matchesselector () returns True if the calling element matches the selector, otherwise, false. However, since not all browsers support this method, we need to write a wrapper function:

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

Second, Element traversal

For spaces between elements, IE9 and previous versions do not return a text node, and other browsers return a text node. Due to inconsistent browser behavior, the following new attributes have been added to the element:

Childelementcount: Returns the number of child elements, excluding text nodes and comment nodes Firstelementchild: points to the first child element, FirstChild element version lastelementchild: points to the last child element, Element version of LastChild previouselementsibling: points to the previous sibling element, previoussibling element version nextelmnetsibling: Point to the next sibling element, NextSibling's element version

With these properties, you can find DOM elements more conveniently without worrying about whitespace characters. The following comparison uses the past methods and the code that uses the new elements:

 var   I, Len, child  = Element.firstchild;  while  (Child!= Element.lastchild) { if  (        Child.notetype = = 1) {Processchild (child);  //  Check if it is an element node  } child  = child.nextsibling;}  
var I,    len,    = element.firstelementchild;  while (Child! = element.lastelementchild)    {if(child.notetype = = 1) {        processchild (child);    }     = child.nextelementsibling;}

Third, HTML5

HTML5 defines a number of JavaScript APIs around how to use new tags, some of which overlap the DOM and define the DOM extensions that the browser should support.

1. Extensions related to the class

<HTML><Head></Head><Body>        <DivID= "Test"class= "Username Current"></Div>        <DivID= "Test1"class= "Current username"></Div><Script>//gets all the elements of the class that contain "Usrname" and "Current", the class name does not mattervarAllcurrentusernames=Document.getelementsbyclassname ("Username Current");varDiv=document.getElementById ("Test");//delete a class in an elementDiv.remove ("username");//Add ClassDiv.add ("username");//Toggle Class: Delete it if it already exists, or add it if it doesn't existDiv.toggle ("username");//determines whether the element contains a classDiv.contains ("username");</Script></Body></HTML>

2. Focus Management

Verify that the user has the focus and know if the user is interacting.

    var button = document.getElementById ("Mybuton");    Button.focus ();     // true

3. Changes in HTMLDocument

1) The readystate attribute of document has two possible values:

Loading, loading the document;

Complete, the document has been loaded.

2) from IE6 to distinguish the mode of rendering page is standard or mixed, testing the compatibility mode of the page becomes the necessary function of the browser. Use Document.compatmode to represent the rendering mode, in standard mode, this value equals "Css1compat", in promiscuous mode, this value equals "Backcompat".

3) as a complement to the <body> element that document.body is a reference document, HTML5 adds a document.head element that represents the

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

4. Character Set properties

HTML5 has added several properties related to the document character set. Document.charset represents the character set that is actually used in the document and can also be used to represent a new character set, and Document.defaultcharset indicates what the default character set should be for the current document based on the default browser and operating system settings.

5. Custom Data Properties

If you need to add some invisible data to the element for additional processing, you need to use the custom data property; The custom attribute needs to add the prefix "data-" to provide the element with no rendering-independent information, or to provide semantic information.

6. Insertion mark

Although the DOM provides a subtle control over the operation of the nodes, it is still very difficult to manipulate the DOM by inserting a large number of HTML tags into the document, as it is not only necessary to create a series of DOM nodes, but also to be careful to connect them in the right way. With insert technology, inserting HTML characters directly can be a lot easier.

1) InnerHTML

innerHTML in read mode, the HTML markup corresponding to all child nodes of the calling element, including elements, annotations, and text nodes, is returned. In write mode, a new DOM tree is created based on the specified value, and the original child nodes of the element are completely replaced with the DOM tree.

2) outerhtml

outerHTML in read mode, the HTML markup corresponding to the calling element itself and all child nodes is returned. In write mode, a new DOM tree is created based on the values executed, and then completely replaced by the DOM itself and the child nodes.

3) insertadjacenthtml ()

This method takes two parameters, inserts the position and the text to be inserted, and the first parameter must be one of the following values:

    • Beforebegin: Inserting an adjacent sibling element before invoking the element
    • Afterbegin: Inserted as the first child element of the calling element
    • BeforeEnd: Inserted as the last child element of the calling element
    • Afterend: Inserted as the last sibling element of the calling element

7. Memory and performance issues

Replacing or deleting a node may cause a memory footprint problem with the browser: When an element is removed from the document tree, the binding relationship between the element and the event handler is not deleted. If this occurs frequently, the amount of memory consumed by the page will increase significantly. Therefore, before using innerhtml/outerhtml/insertadjacenthtml, it is a good idea to manually delete all the things handlers and JavaScript object properties of the element to be replaced.

8, scrollIntoView ()

scrollIntoView () can be called on all HTML elements, and if the method is passed true for arguments, or if no parameters are passed in, the window will be scrolled so that the top of the calling element is flush with the top of the viewport as much as possible. If False is passed as a parameter, the calling element appears as full as possible in the viewport.

Third, proprietary extensions

While all browser vendors know the importance of adherence to standards, they will continue to add proprietary extensions to the DOM as usual to compensate for the lack of functionality, which, once recognized, may be included in a new version of the specification. Some proprietary extensions are described below:

1. Document mode

Document mode is the concept introduced by IE, the document mode of the page determines which level of CSS the document can use, which APIs can be used in JavaScript, and how to treat the document type (DOCTYPE).

2. Contains method

The Contains method is used to determine whether a node is a child node of the calling node.

3. Inserting text

1) innertext Property

With the InnerText property, you can manipulate all the contained text nodes in an element.

<HTML>    <Head></Head>    <Body>        <DivID= "Content">            <P>This is a paragragh.</P>            <ul>                <Li>Item 1</Li>                <Li>Item 2</Li>                <Li>Item 3</Li>            </ul>        </Div>    </Body></HTML>

For this example, InnerText will return:

    • This is a paragragh.
    • Item 1
    • Item 2
    • Item 3

If you set the text through innertext, the child nodes under the calling element are deleted, plus the text node, which completely alters the DOM tree.

2) Outertext

In read mode, outertext and innertext are exactly the same, in write mode, the outertext will first delete the call node itself and the child nodes, and then add the text node.

JavaScript Advanced Programming DOM Extensions

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.