JavaScript: The Definitive Guide, Sixth Editio javaScript权威指南(第6版) pdf 文字版-文字版, javascript电子书, 和javascript 有关的电子书:

15.2.4 Selecting Elements by CSS Class

15.2.4 Selecting Elements by CSS Class


The class attribute of an HTML is a space-separated list of zero or more identifiers. It describes a way to define sets of related document elements: any elements that have the same identifier in their class attribute are part of the same set. class is a reserved word in JavaScript, so client-side JavaScript uses the className property to hold the value of the HTML class attribute. The class attribute is usually used in conjunction with a CSS stylesheet to apply the same presentation styles to all members of a set, and we’ll see it again in Chapter 16 . In addition, however, HTML5 defines a method, getElementsByClassName(), that allows us to select sets of document elements based on the identifiers in their class attribute.

Like getElementsByTagName(), getElementsByClassName() can be invoked on both HTML documents and HTML elements, and it returns a live NodeList containing all matching descendants of the document or element. getElementsByClassName() takes a single string argument, but the string may specify multiple space-separated identifiers. Only elements that include all of the specified identifiers in their class attribute are matched. The order of the identifiers does not matter. Note that both the classattribute and the getElementsByClassName() methods separate class identifiers with spaces, not with commas. Here are some examples of getElementsByClassName():

// Find all elements that have "warning" in their class attribute var warnings = document.getElementsByClassName("warning");

// Find all descendants of the element named "log" that have the class // "error" and the class "fatal" var log = document.getElementById("log"); var fatal = log.getElementsByClassName("fatal error");

Today’s web browsers display HTML documents in “quirks mode” or “standards mode” depending on how strict the declaration at the start of the document is. Quirks mode exists for backward compatibility, and one of its quirks is that class identifiers in the class attribute and in CSS stylesheets are case-insensitive. getElementsByClassName() follows the matching algorithm used by stylesheets. If the document is rendered in quirks mode, the method performs a case-insensitive string comparison. Otherwise, the comparison is case sensitive.

At the time of this writing, getElementsByClassName() is implemented by all current browsers except IE8 and earlier. IE8 does support querySelectorAll(), described in the next section, and getElementsByClassName() can be implemented on top of that method.

欢迎转载,转载请注明来自一手册:http://yishouce.com/book/1/31424.html
友情链接It题库(ittiku.com)| 版权归yishouce.com所有| 友链等可联系 admin#yishouce.com|粤ICP备16001685号-1