1.DOM Extensions
①The two primary standards specifying DOM extensions are the Selectors API(选择符API) and HTML5.
2.Selectors API
①Indeed(实际上),the library jQuery is built completely around the CSS selectors queries of a DOM document in order to retrieve references to elements instead of using getElementById() and getElementsByTagName().
②At the core of Selectors API Level 1 are two methods:querySelector() and querySelectorAll().On a conforming(兼容的) browser,these methods are available on the Document type and on the Element type.Selectors API Level 1 was fully implemented in Internet Explorer 8+,Firefox 3.5+,Safari 3.1+,Chrome,and Opera 10+.
+③The querySelector() method accepts a CSS query and returns the first descendant(后代的) element that matches the pattern or null if there is no matching element.When the querySelector() method is used on the Document type,it starts trying to match the pattern from the document element;when used on an Element type,the query attempts to make a match from the descendants of the element only.
//获得body元素
var body=document.querySelector('body');
//获得ID为"myDiv"的元素
var myDiv=document.querySelector('#myDiv');
//获得类为"selected"的第一个元素
var selected=document.querySelector('.selected');
//获得类为"button"的第一个图像元素
var img=document.body.querySelector('img.button');
④The querySelectorAll() method accepts the same single argunment as querySelector() —-the CSS query—but returns all matching nodes instead of just first one.This method returns a static instance of NodeList.
+⑤As with querySelector(),the querySelectorAll() method is available on the Document,DocumentFragment and ELement types.
//获得某<div>元素中的所有<em>元素,(类似于getElementsByTagName('em'))
var ems=document.getElementById('myDiv').querySelectorAll('em');
//获得类为"selected"的所有元素
var selecteds=document.querySelectorAll('.selected');
//获得所有<p>元素中的所有<strong>元素
var strongs=document.querySelectorAll('p strong');
//要想获得返回的NodeList中的每个元素,可以使用item()或方括号语法
var i,len,strong;
for(i=0,len=strongs.length;i<len;i++){
strong=strongs[i];//strong=strongs.item(i);
strong.className='important';
}
+⑥The Selectors API Level 2 specification(规范) introduces another method called matchesSelector() on the Element type.This method accepts a single argument,a CSS selector,and returns true if the given element matches the selector or false if not.
if(document.body.matchesSelector('body.page1')){
//true
}
function matchesSelectorFunction(element,selector){
if(element.matchesSelector){
return element.matchesSelector(selector);
}else if(element.msMatchesSelector){ //IE 9+
return element.msMatchesSelector(selector);
}else if(element.mozMacthesSelector){ //Firefox 3.6+
return element.mozMacthesSelector(selector);
}else if(element.webkitMacthesSelector){ //Safari 5+ and Chrome
return element.webkitMacthesSelector(selector);
}
}
//调用函数
if(matchesSelectorFunction(document.body,'body.page1')){
//do something.
}
3.Element Traversal
+①Prior to version 9,Internet Exploere did not return text nodes for white space in between elements while all of the other browsers did.The Element Traversal API adds five new properties to DOM elements:
a)childElementCount—-Returns the number of the child elements(excludes[不包括] text nodes and comments).
b)firstElementChild—-Points to the first child that is an element.Element-only version(元素版) of firstChild.
c)lastElementChild—-Points to the last child that is an element.Element-only version of lastChild.
d)perviousElementSibling—-Points to previous sibling that is an element.Element-only version of previousSibling.
e)nextElementSibling—-Points to the next sibling that is an element.Element-only version of nextSibling.
//before
var i,len;
var child=element.firstChild;
while(child!=element.lastChild){
if(child.nodeType==1){ //check for an element
processChild(child);
}
child=child.nextSibling;
}
//now
var i,len;
var child=element.firstElementChild;
while(child!=element.lastElementChild){
processChild(child); //already know it's an element
child=child.nextElementSibling;
}
②Element Traversal is implemented in Internet Explorer 9+,Firefox 3.5+,Safari 4+,Chrome and Opera 10+.
4.Class-Related Additions(与类相关的扩充)
+①The getElementsByClassName() method accepts a single argument,which is a string containing one or more class names,and returns a NodeList containing all elements thay have all of the specified(指定的) class applied.If multiple class names are specified,then the order is considered unimportant.
//获取所有类中包含"username"和"current"的元素,类名的先后循序无所谓
var allCurrentUsernames=document.getElementsByClassName('username current');
//获取ID为"myDiv"的元素中带有类名为"selected"的所有元素
var selected=document.getElementById('myDiv').getElementsByClassName('selected');
②The getElementsByClassName() method was implemented in Internet Explorer 9+,Firefix 3+,Safari 3.1+,Chrome and Opera 9.5+.
5.The classList Property
+①In class name manipulation,the className property is used to add,remove and replace class names.Since className contains a single string,it's necessary to set its value every time a change needs to take place,even if there are parts of the string that should be unaffected.
<div class='yyc asan pangzi'>...</div>
//删除"yyc"类---【分】-【删】-【合】
//先获取<div>元素中的所有类名,然后按空白符拆分成数组
var classNames=div.className.split(/\s+/);//正则表达式:分离任何空白符(空格,回车,tab..)
var pos=-1;
var i,len;
for(i=0,len=classNames.length;i<len;i++){
//找出想要删除的数组
if(classNames[i]=='yyc'){
pos=i;
break;
}
}
//删除该类名
classNames.splice(i,1);//arrayObject(index,howmany,item1,item2...itemX)
//最后再聚合
div.className=classNames.join(' ');
//或用一个新的元素属性---classList,以上代码只需一行即可----省事
div.classList.remove('yyc');
+②HTML5 introduces a way to manipulate class names in a much simpler and safer manner through the addtion of the classList property for all elements.The classList property is an instance of a new type of collection named DOMTokenList.As with other DOM collections,DOMTokenList has a length property to indicate how many items it contains,and individual items may be retrieved via the item() method or using bracket notation(方括号表示法).It also has the following additional methods:
a)add(value)—Adds the given string value to the list.If the value already exists,it will not be added.
b)contains(value)—-Indicates if the given value exists in the list(true if so;false if not).
c)remove(value)—Removes the given string value from the list.
d)toggle(value)—-If the value already exists in the list,it is removed.If the value doesn't exist,then it's added.
//其他示例
div.classList.remove('asan');
div.classList.add('qin');
div.classList.toggle('laowang');//有则"删"之,无则加之
//判断元素中是否存在既定类名
if(div.classList.contains('pangzi') && !div.classList.contains('asan')){
//do something
}
//迭代类名
for(var i=0,len=div.classList.length;i<len;i++){
doSomething(div.classList[i]);
}
③The addition of the classList property makes it unnecessary to access the className property unless you intend to completely remove or completely overwrite the element's class attribute.The classList property is implemented in Firefox 3.6+ and Chrome.
6.Focus Management
+①HTML5 adds functionality to aid with(帮助) focus management in the DOM.The first is document.activeElement,which always contains a pointer to the DOM element that currently has focus.An element can receive focus automatically as the page is loading,via user input(用户输入)(typically using the Tab key),or programmatically(以编程的方式) using focus() method.
var button=document.getElementById('myButton');
button.focus();
alert(document.activeElement===button);//true
②By default,document.activeElement is set to document.body when the document is first loaded.Before the document is fully loaded,document.avtiveElement is null.
+③The second addtion is document.hasFocus(),which returns a Boolean value indicating if the document has focus.
var button=document.getElementById('myButton');
button.focus();
alert(document.hasFocus());//true----文档是否获得焦点
④These properties are implemented in Internet Explorer 4+,Firefox 3+,Safari 4+,Chrome and Opera 8+.
7.Changes to HTMLDocument
①Internet Explorer 4 was the first to introduce a readyState property on the document object.Other browsers then followed suit and this property was eventually formalized in HTML5.The readyState property for document has two possible values:
a)loading—-The document is loading.
b)complete—The document is completely loaded.
+②The best way to use the document.readyState property is as an indicator than the document has loaded.
if(document.readyState=='complete'){
//do something
}
③The readyState property is implemented in Internet Explorer 4+,Firefox 3.6+,Safari,Chrome and Opera 9+.
④When in standards mode,document.compatMode is equal to “CSS1Compat”;when in quirks mode(混杂模式),document.compatMode is “BackCompat”
if(document.compatMode=='CSS1Compat'){
alert('standards mode');
}else{
alert('quirks mode');
}
⑤The document.compatMode property is implemented in Internet Explorer 6+,Firefox,Safari 3.1+,Opera and Chrome.As a result,the property was added to HTML5 to formalize its implementation.
⑥HTML5 introduces document.head to point to the <head> element of a document to complement document.body,which points to the <body> element of the document.You can retrieve(获取) a reference to the <head> element using this property or the fallback(后备) method.
+⑦This code uses document.head,if available;otherwise it falls back to the old method of using getElementsByTagName().The document.head property is implemented in Chrome and Safari 5.
var head=document.head||document.getElementsByTagName('head')[0];
8.Charater Set Properties
+①The charset property indicates the actual character set being used by the document and can also be used to specify a new character set.By default,this value is “UTF-16”,although it may be changed by using<meta> elements or response headers or through setting the charset property directly.
alert(document.charset);//"UTF-16"
document.charset='utf-8';
+②The defaultCharset property indicates what the default character set for the document should be bases on default browser and system settings.The value of charset and defaultCharset may be different if the document doesn't use the default character set.
if(document.charset != document.defaultCharset){
alert('Custom character set being used');//自定义的字符集
}
③The document.charset property is supported by Internet Explorer,Safari,Opera and Chrome.[Firefox—-document. Characterset 只读]The document.defaultCharset property is supported in IE,Safari and Chrome.
9.Custom Data Attributes
①HTML5 allow elements to be specified with nonstandard attributes prefixed(添加前缀) with data- in order to provide information that isn't necessary to the rendering(映射) or semantic(语义的) value of the element.
+②When a custom data attribute is defined,it can be accessed via the dataset property of the element.The dataset property contains an instance of DOMStringMap that is a mapping of name-value pairs.Each attribute of the format data-name is represented by a property with a name equivalent to the attribute but without the data- prefix.(for example,attribute data-myname is represented by a property called myname).
<div id='myDiv' data-appId='12345' data-myname='yyc'></div>
var div=document.getElementById('myDiv');
var appId=div.dataset.appId;
var myname=div.dataset.myname;
div.dataset.appId='54321';
div.dataset.myname='Gerg';
10.Markup Insertion
①Although the DOM provides fine-grained(细致入微) control over nodes in a document,it can be cumbersome(冗长的) when attempting to inject(插入) a large amount of new HTML into the document.Instead of creating a series of DOM nodes and connecting them in the correct order,it's much easier(and faster) to use one of the markup insertion(插入标记) capabilities to inject a string of HTML.The following DOM extensions have been standardlized in HTML5 for this purpose.
+②When used in read mode,innerHTML returns the HTML representing all of the child nodes,including elements,comments and text nodes.When used in write mode,innerHTML completely replaces all of the child nodes in the element with a new DOM subtree based on the specified value.
<div id='content'>
<p>This is a<strong>paragraph</strong> with a list following it/</p>
<ul>
<li>Item1</li>
<li>Item2</li>
<li>Item3</li>
</ul>
</div>
var div=document.getElementById('content');
div.innerHTML;
/*
<p>This is a<strong>paragraph</strong> with a list following it/</p>
<ul>
<li>Item1</li>
<li>Item2</li>
<li>Item3</li>
</ul>
*/
div.innerHTML='Hello world.';
div.innerHTML="Hello & welcome,<b>\"reader\"!</b>";
//<div id='content'>Hello & welcome,<b>"reader"!</b></div>
div.innerHTML="_<style type=\"text/css\">body {background-color:orange;}</style>"
div.removeChild(div.firstChild);
③The innerHTML property is not available on all elements.The following elements do not support innerHTML:<col>,<colgroup>,<frameset>,<head>,<html>,<style>,<table>,<tbody>,<thead>,<tfoot> and <tr>.Additionally,IE 8- do not support innerHTML on the <title> element.
④When outerHTML is called in read mode,it returns the HTML of the element on which it is called,as well as its child nodes.When called in write mode,outerHTML replaces the node on which it is called with the DOM subtree created from parsing the given HTML string.
var div=document.getElementById('content');
div.outerHTML;
/*
<div id='content'>
<p>This is a<strong>paragraph</strong> with a list following it/</p>
<ul>
<li>Item1</li>
<li>Item2</li>
<li>Item3</li>
</ul>
</div>
*/
div.outerHTML='<p>This is a paragraph.</p>';
//DOM脚本代码【同上】
var p=document.createElement('p');
p.appendChild(document.createTextNode('This is a paragraph.'));
div.parentNode.replaceChild(p,div);
//新创建的P元素取代DOM树中的<div>元素
⑤The outerHTML property is supported by IE 4+,Safari 4+,Chrome,Opera 8+ and Firefox 7+.
11.The insertAdjacentHTML() Method
+①The last addtion for markup insertion is the insertAdjacentHTML() method.This method also originated in IE and accepts two arguments:the position in which to insert and the HTML text to insert.
//作为前一个同辈元素插入
element.insertAdjacentHTML('beforebegin','<p>Hello yyc.</p>');
//作为第一个子元素插入(begin)
element.insertAdjacentHTML('afterbegin','<p>Hello yyc.</p>');
//作为最后一个子元素插入(end)
element.insertAdjacentHTML('beforeend','<p>Hello yyc.</p>');
//作为后一个同辈元素插入
element.insertAdjacentHTML('afterend','<p>Hello yyc.</p>');
②The insertAdjacentHTML() method is supported in IE,Firefox 8+,Safari,Opera and Chrome.
12.Memory and Performance Issues
①When using innerHTML,outerHTML and insertAdjacentHTML(),it's best to manually(手动地) remove all event handlers and JavaScript object properties on elements that are going to be removed.
13.scrollIntoView Method
①The scrollIntoView() method exists on all HTML elements and scrolls the browser window or container element so the element is visible(可见的) in the viewport.If an argument of true is supplied or the argument s omitted(省略),the window scrolls so that the top of the element is at the top of the viewport(if possible);otherwise,the element is scrolled so that it is fully visible in the viewport but may not be aligned(对齐,调整) at the top.
②The scrollIntoView() method is suported in IE,Firefox,Safari,Opera and Chrome.
14.Document Mode
①A page's(文档) document mode determines to which features it has access.This means that there's a specific(具体的,明确的) level of CSS support,a specific number of features available for scripting through JavaScript,a specific way that doctypes are treated.
②As of IE 9(IE9之前),there are four different document modes:
a)IE 5—Renders the page(渲染页面) in quirks mode(the default mode for IE 5).The new features in IE 8+ are not available.
b)IE 7—Renders the page in IE 7 standards mode.The new features in IE 8+ are not available.
c)IE 8—Renders the page in IE 8 standards mode.New features in IE 8 are available,so you can access the Selectors API,more CSS2 selectors,some CSS3 features,some HTML5 features.The IE 9 features are not available.
d)IE 9—Renders the page in IE 9 standards mode.New features in IE 9 are available,such as ES5,full CSS3 support and more HTML5 features.This document mode is considered the most advanced.
③You can determine the document mode for a given page using the document.documentMode property.
15.The children Property
①The differences in how IE 9- and other browsers interpret white space in text nodes led to the creation of the children property.The children property is an HTMLCollection that contains only an element's child nodes that are also elements.Otherwise,the children property is the same as childNodes and may contain the same items when an elements has only elements as children.
②The children collection is supported in IE5,Firefox 3.5,Safari 2(buggy),Safari 3(complete),Opera 8 and Chrome(all versions).IE 8- also return comments in the children collection(while IE9+ do not).
16.The contains() Method
①contains()方法的作用:判断某个节点是不是另一个节点的后代。
②The contains() method is supported in IE,Firefox 9+,Safari,Opear and Chrome.
③DOM Level 3 compareDocumentPosition()方法,支持的浏览器:IE9+,Opera 9.5+,其他三剑客。返回表示关系的位掩码(bitmask)【a.compareDocumentPosition(b)】—-1:无关/2:b在a前/4:居后/8:包含/16:被包含—-2^0/2^1/2^2/2^3/2^4
+④
function contains(refNode,otherNode){
//检测参考节点是够具有contains()方法以及当前浏览器所用的WebKit版本号
if(typeof refNode.contains=='function'&&
(!client.engine.webkit)||client.engine.webkit>=522){
return refNode.contains(otherNode);
//检测参考节点是够具有compareDocumentPosition()方法
}else if(typeof refNode.compareDocumentPosition=='function'){
//只要otherNode是refNode的子代,位掩码:4(居后)+16(被包含)=20,所以返回true
return !!(refNode.compareDocumentPosition(otherNode)&16);
}else{
//自otherNode节点一步步遍历至文档树顶端---到null
var node=otherNode.parentNode;
do{
if(node==refNode){
return true;
}else{
node=node.parentNode;
}
}while(node!==null);
return false;
}
}