JS Magic Hall: The DOM collection type that bothers you

Source: Internet
Author: User
Tags object object throw exception

First, preface

Everyone first look at the following JS, guess what the results will be!

Optional answers:

①. Get the node element with ID attribute value ID

②. Throwing Nameditem is undefined exception

var nodes = document.getelementsbyname ('dummyname'); var node = nodes.nameditem ('ID');

The answer is that both of them are possible Oh! Document.getelementsbyname in Chrome and FF30.0 back to NodeList (wood with Nameditem method), in the whole series of IE return htmlcollection, vomiting blood it?

Dom Collection is more than that, let's discuss it together!

Second, the nodelist and htmlcollection that troubled you and me

  Same point:

1. An array of classes. There is the Length property, you can use subscript index to access the elements, but there is no array of slice and other methods;

2. Read-only. Unable to delete the elements;

3. Synchronize the DOM tree changes in real time. If a new element is added to the DOM tree, the object of that type will also include the new element;

4. The element of the specified position in the collection can be obtained by subscript numeric type index;

5. You can use the item ({String | Number} method gets the element at the specified position in the collection, with the first element being the return value if the element cannot be found through the index.

  Different points (mainly manifested in htmlcollection than nodelist ability more powerful):

1. The Htmlcollection object can get the first matching element by Nameditem ({String} ID or name), or null if none;

2. The Htmlcollection object can get the element with the first ID or name matching by point, and if not, returns undefined.

Different browser selector return type differences:

//IE678 return [Object Object] object with Htmlcollection feature (with Nameditem method)
IE9, 10, 11, FF, chrome all return htmlcollectiondocument.images;document.links;document.anchors;document.forms;document.embeds;document.scripts; Document.applets;document.plugins; Node object. getElementsByTagName; Node object. getelementsbytagnamens; Node object. getelementsbyclassname; Htmltableelement object. tbodies; Htmltableelement object. Children; Htmltableelement object. Rows; Htmltablerowelement object. Cells; Htmlmapelement object. Areas;
//IE678 return [Object Object] object with Htmlcollection feature (with Nameditem method)
IE9, 10, 11 return htmlcollection//FF30.0, chrome back nodelistDocument.getelementsbyname;//IE678 return [Object Object] object with NodeList feature (no Nameditem method)
IE9, 10, 11, FF, chrome all return nodelistnode object. childNodes;//IE5678 return [Object Object] object with Htmlcollection feature (with Nameditem method)//IE9, 10 returns [Object Htmlcollection]//IE11, chrome back [object Htmlallcollection]//FF30.0 return [object HTML document.all class]document.all;

1. In general, the implementation of Chrome is closer to the specification;

2. Htmlallcollection, Htmlcollection, and [object HTML document.all class] functions are no different, except for the type;

3. Because document.getelementsbyname returns different types of objects in different browsers, it is easier to use the [{number} index] method to access the collection elements.

4. Digression: The Children property only gets the element with NodeType 1, and ChildNodes will include all the child elements in it;

5. Note: IE9, 10, 11 htmlcollection and other browsers htmlcollection can be different oh, please see the next section!

Three, the same name different sex--ie under the strange htmlcollection

If you have seen "JS Magic Hall: Recalling those original selectors", it should be understood that under IE5678, Document.all will return a class function object, which is mentioned above with the Htmlcollection feature of the [Object Object] objects. In fact, ie this tradition has continued to IE11, which led to IE9, 10, 11 under the htmlcollection and the standard of the same name and different nature of the problem.

What is a class function?

It is purely my own definition, used to refer to those features that have functions, but instanceof function returns false object.

Really want to say to ie, you so hanging, your mother know?

Four, staticnodelist--disguised as a nodelist boy

There is a Queryselectorall selector method starting from IE8. The specific behavior is as follows:

// IE8 returns [Object Object], ie9+ and Chrome, FF return [object NodeList] var nodes =  document.queryselectorall ('*'); // IE8 Returns an empty set [object object],ie9+ and Chrome, FF is thrown at least 1 function-parameter exceptions nodes = document.queryselectorall (); // each browser throws SyntaxError exception nodes = Document.queryselectorall (") or Document.queryselectorall ( Non-string type into the parameter);

Everyone should not be deceived by the nodelist returned by the browser, in fact Queryselectorall returned is Staticnodelist object. Its characteristics and nodelist are basically the same, the only difference is that staticnodelist is not the real-time synchronization of DOM tree changes, so in the Polyfill queryselectorall time does not have to consider the real-time synchronization dom tree change problem.

Htmloptionscollection--htmlcollection subclasses of the five,

The Htmlselectelement object. Options returns an Htmloptionscollection collection object that stores elements of the htmloptionelement type in the collection. Htmloptionscollection types In addition to the characteristics of the parent class htmlcollection, there are the following member methods, properties available.

// adds an OPTION element to the end of the collection, or the specified element (position) after remove ({number} index); // Delete options at the specified location // index of the currently selected item, starting at 0

Vi. sub-categories of htmlformcontrollerscollection--htmlcollection

The Htmlformelement object. Elements returns a Htmlformcontrollerscollection collection object that stores various form elements within the collection. What's special about this is that when you get an ID or name-matched element from a point property, the generic Htmlcollection collection object returns only the first matching element, even if there are multiple matching elements; Htmlformcontrollerscollection, This element is returned when there is a matching element, and a Radionodelist collection object is returned if there are multiple matching elements.

Vii. Subclasses of Radionodelist--nodelist

At first glance Radionodelist is likely to think that the collection element is a single-selection form element, in fact radionodelist can store any type of form element. The Value property, however, shows values of the single-option form element that is selected, if there is no single-option form element, or if the single-option form element is not selected, the value is an empty string.

Viii. Subclasses of Htmlallcollection--htmlcollection

IE11, Chrome starts, document.all will return the object of the Htmlcollection subclass Htmlallcollection, with the same behavioral characteristics as htmlcollection. But the htmlallcollection in IE11 can also be used as a function, see section III of this article for details.

Nine, namednodemap--unordered attr elements Collection

The HtmlElement object. Attributes returns the NamedNodeMap collection object, which internally holds an object of type [object Attr]. NamedNodeMap and Htmlcollection, nodelist, are different because it is an unordered collection, although the elements in the NamedNodeMap collection can be accessed through a numeric type of subscript index, but the index value does not truly represent the position of the element in the collection. Here are the member methods of NamedNodeMap:

Item ({number |  // returns the specified attribute node by name // returns the specified attribute node by name and namespace // setting the specified attribute node by name // setting the specified attribute node by name and namespace // delete the specified attribute node by name // delete the specified attribute node by name and namespace

Note: The HtmlElement object. Attributes returns only the display properties (simply the properties that are written directly on the HTML tag, or properties that are set through setattribute, see the JS Magic Hall: Do not be attribute and property troubled us again ")

Ten, the DOMTOKENLIST--HTML5 new characteristic classlist type Oh!

Used Classlist know it greatly improved the efficiency of the CSS class we set, but IE10 the following is not supported, Polyfill can help us. But before Polyfill, we should first understand the characteristics of classlist type domtokenlist.

1. Read-only

2. Real-time synchronization of the corresponding elements of the classname attribute value changes

3. Have the following methods and properties

class // classes that already exist are not added repeatedly {Undefined}  class {  Undefined}class class// Check if there is a specified class / / get the class at the specified location by index //  //  Cannot set class by [{number} index], only to get class in this way

So now we're going to polyfill it, pay attention to the difficulties in real-time synchronization of this piece, the solution is to use Onpropertychange to monitor the change of classname (to learn more, see "JS Magic Hall: The Observer of the DOM World")

function Polyfillclasslist (EL) {varr =/\s+/, CLS = el.classname, _inner = cls?Cls.trim (). Split (R): []; varListener =function (e) {if(E.propertyname!=='ClassName')return void 0; varCLst = el.classlist, OLen = _inner.length, cls=El.classname; _inner= CLS?Cls.trim (). Split (R): []; varLen = (Clst.length =_inner.length);  for(vari =0, MaxLen = Math.max (OLen, Len); i < MaxLen; ++i) {       if(I <Len) {Clst[i]=_inner[i])} Else{delete Clst[i];  }    }      }; El.attachevent ('Onpropertychange', listener); El.classlist={length: _inner.length, item:function (index) {return_inner[index] | |NULL; }, Add:function (CLS) {//omit code that checks whether the CLS value is valid       if( This. Contains (CLS))return void 0; El.detachevent ('Onpropertychange', listener); El.classname+=' '+CLS;       _inner.push (CLS);  This[ This. length++] =CLS; El.attachevent ('Onpropertychage', listener); }, Remove:function (CLS) {//omit code that checks whether the CLS value is valid       if(! This. Contains (CLS))return void 0; El.detachevent ('Onpropertychange', listener); El.classname= El.className.replace (NewREGEXP ('\\b'+ CLS +'\\b','I'),"'). Trim (); _inner.splice (_inner.indexof (CLS),1); -- This. Length; El.attachevent ('Onpropertychage', listener); }, Toggle:function (CLS) {//omit code that checks whether the CLS value is valid        This[ This. Contains (CLS)?'Remove':'Add'] (CLS); }, Contains:function (CLS) {//omit code that checks whether the CLS value is valid       returnEl.className.search (NewREGEXP ('\\b'+ CLS +'\\b','I')) >=0; }, Tostring:function () {return_inner.tostring ();    }  }; //initialize Classlist[{number} index] get attr element   for(vari =0, Len = _inner.length; i < Len; ++i) {El.classlist[i]=_inner[i]; }}        

Because Invalidcharactererror is thrown when the parameter values of the native Add, remove, contains, and toggle methods contain spaces, a corresponding check and throw exception is made at Polyfill.

//Analog Invalidcharactererror classvarInvalidcharactererror =function (msg) { This. Code =5;  This. Message =msg;  This. Name ='Invalidcharactererror';};i Nvalidcharactererror.prototype=domexception;//Check for parameters and throw exceptions//@param {String} methodName Add, remove, and other method names//@param {String} cls CSS classvarCheck =function (MethodName, CLS) {varMSGTPL = ["Failed to execute '", ,"' on ' domtokenlist ': the token provided ('", ,"') contains HTML space characters, which is not valid in tokens."]; if(/\s+/. Test (CLS)) {     Throw NewInvalidcharactererror ((msgtpl[1] = MethodName, msgtpl[3] = CLS, MSGTPL). Join ("')); }};

For more information on exception handling, error and exception, please note the JS Magic Hall: Exception handling is not so simple

Xi. Summary

In fact, the collection of DOM is more than these, in the following days I will learn while perfecting this article, thank you for watching!

Respect the original, when reproduced please indicate from: http://www.cnblogs.com/fsjohnhuang/p/3819165.html ^_^ Fat Boy John

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.