Javascript - document物件
名稱 | 類形 | 說明 |
---|---|---|
document | 物件 | document物件是window的屬性之一,自瀏覽器引入Javascript開始就提供的一種物件,主要用於獲取和修改一些頁面的屬性以及屬性集合; 由於window物件的任何屬性和方法都可以直接訪問,因此下例程式碼返回的值為true。 例:alert(window.document == document); |
DOMContentLoaded | 事件屬性 |
DOMContentLoaded事件是當文件中的Dom tree建立完成並能被script存取後被觸發; 它不像load事件需要等所有外部資源(images, iframe, plugins...)載入後才觸發,但有一個例外的特性,就是當<script>被放在<link rel="stylesheet" ...>後面的話,須等到前面的stylesheet載入並完成解析,此時DOMContentLoaded才會被觸發。 注意一定要用addEventListener來接這個事件,不能寫成document.onDOMContentLoaded = ...喔 IE8不支援DOMContentLoaded,但可以使用readystatechange事件來做降解,如下例: if(document.addEventListener){ document.addEventListener('DOMContentLoaded',function(){ console.log('支援DOMContentLoaded事件'); }); }else{ document.onreadystatechange=function(){ if(document.readyState=='complete'){ console.log('不支援DOMContentLoaded事件'); } } } console.log('程式走到這裡就先執行了'); |
alinkColor | 屬性 | |
body | 屬性 | References the body element of the page. From there, you can then access other nodes contained within the body. |
all | 屬性 | 頁面中所元素的集合,例如document.all(0)代表頁面內的第一個素;它是IE專用的屬性,所以常常用來判斷使用者的瀏覽器是否為IE瀏覽器,如下例:
if(document.all){alert('是IE瀏覽器');} |
anchors | 屬性 | 頁面中所有錨的集合(<a name="anchorsName"></a>)。 |
applets | 屬性 | 頁面中所有的applet集合。 |
bgColor | 屬性 | |
compatMode | 屬性 | Returns the compatibility mode of the current document, specifically, whether the page is rendered in Quirks or Stricts mode. The two possible values returned are "BackCompat" for Quirks and "CSS1Compat" for Strict. Useful for determining the doctype setting of the page and executing different code accordingly. Example:
if (document.compatMode=="CSS1Compat"); // execute code for page with a valid doctype |
cookie | 屬性 |
建立cookie:
document.cookie = "username=John Doe"; //預設在關掉瀏覽器後就消失加上到期時間(UTC time): document.cookie = "username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC";設置path參數;預設為當前頁面: document.cookie = "username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/";取得cookie: var x = document.cookie; //會得到一個像這樣的字串:"cookie1=value; cookie2=value; cookie3=value;"改變cookie的值: document.cookie = "username=John Smith; expires=Thu, 18 Dec 2013 12:00:00 UTC;";刪除cookie: document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"; //將時間設為過去※:我們應該要指派cookie的path值,以免我們刪錯cookie;如果沒有指派,有的瀏覽器會不讓我們刪cookie 包裝建立cookie的function: function setCookie(cookie_name, cvalue, exdays) { var d = new Date(); d.setTime(d.getTime() + (exdays*24*60*60*1000)); var expires = "expires="+ d.toUTCString(); document.cookie = cookie_name + "=" + cvalue + ";" + expires + ";path=/"; }包裝取cookie值的function: function getCookie(cookie_name) { var name = cookie_name + "="; var decodedCookie = decodeURIComponent(document.cookie); var ca = decodedCookie.split(';'); for(var i = 0; i <ca.length; i++) { var c = ca[i]; while (c.charAt(0) == ' ') { c = c.substring(1); } if (c.indexOf(name) == 0) { return c.substring(name.length, c.length); } } return ""; } |
doctype | 屬性 | Read-only property that returns the Document Type Definition (DTD) of the current document, or null if the page doesn't contain a DTD. Not supported in IE as of IE6. |
documentElement | 屬性 | References the root element of the document, in the case of HTML documents, the html element. This read only property is useful for accessing all elements on the page, such as the HEAD. Example:
entiredoc = document.documentElement; var elements=entiredoc.getElementsByTagName("*"); for (i=0; i<elements.length; i++) alert(elements[i].tagName) |
domain | 屬性 | Gets/sets the domain of the current document. Useful in cross domain scripting when one domain is to communicate with another. Example:
document.domain="javascriptkit.com" |
embeds | 屬性 | 頁面中所有的內置物件集合(<embed></embed>)。 |
fgColor | 屬性 | |
fileSize | 屬性 | |
forms[] | 屬性 | 指向文件中所有<FORM>元素的清單陣列,它的一系列屬性、事件及方法請見DOM Objects的form物件。 範例:列出各種拜訪表單及其元素的寫法 <form name="form_name" id="form_id"> <input type="text" name="text_name" id="text_id" /> <input type="submit" name="submit_name" id="submit_id" value="送出" /> </form> <form name="form2" id="form2"> <input type="text" /> </form> <script> var my_form = document.forms; var my_form2 = document.form2; //直接使用name屬性拜訪表單 document.write(my_form['form_name'].name+'<br>'); document.write(my_form.form_name.name+'<br>'); document.write(my_form['form_id'].id+'<br>'); document.write(my_form.form_id.id+'<br>'); document.write(my_form.length+'<br>'); document.write(my_form[0].elements[0].type+'<br>'); document.write(my_form[0].elements[0].tagName+'<br>'); document.write(my_form[0].elements['text_id'].id+'<br>'); document.write(my_form[0].elements['text_name'].name+'<br>'); document.write(my_form[0].elements.text_id.id+'<br>'); document.write(my_form[0].getElementsByTagName('input')[1].id+'<br>'); document.write(my_form[0].getElementsByTagName('input')[1].getAttribute('name')+'<br>'); document.write(my_form2.name); </script> 結果:form_name form_name form_id form_id 2 text INPUT text_id text_id submit_id submit_name form2由上例看來forms也可以和DOM level 2的各種屬性及方法混用,不過"精通Javascript+jQuery"書中第7-27頁提到:傳統訪問表單元素的方法比較方便向伺服器傳送資料。因為選項案鈕各項之間name的值相同,而id值不同。( 雖然看不懂在寫什麼…但就先記錄下來… ) |
images | 屬性 | 頁面中所有的圖片集合。 |
implementation | 屬性 | Returns the DOM implementation of the current document. |
lastModified | 屬性 | |
linkColor | 屬性 | |
links | 屬性 | 頁面中所有的超連結集合(<a href="URL"></a>)。 |
plugins | 屬性 | |
readyState | 屬性 | Returns the loading status of the document. It returns one of the below 4 values:
uninitialized :The document hasn't started loading yet.
Use the onreadystatechange event handler to react whenever the readyState of the document changes. For example:
loading :The document is loading. interactive :The document has loaded enough whereby user can interact with it. complete :The document has fully loaded. document.onreadystatechange=function(){ if (document.readyState=="complete"){ alert("Document loaded fully!"); } } |
referrer | 屬性 | |
styleSheets | 屬性 | styleSheets物件是document下的一個屬性,它記載了頁面中的樣式表的陣列,包括使用<style>標籤撰寫的樣式表,以及使用<link>標籤載入的樣式表;使用@import的樣式表或是寫在行內的樣式則不在此列; 此物件也擁有一系列的屬性、方法及子物件,詳細內容請見"DOM - styleSheets"一節。 以下的範例將傳回頁面中樣式表的數量及類型: window.onload = function(){ var s = document.styleSheets; alert(s.length +"\n"+ s[0].type); } |
title | 屬性 | Specifies the title of the document. Read/write in modern browsers. |
URL | 屬性 | 原文:A string that specifies the complete URL of the document. 獲取目前頁面的URL,或將其設置新的URL,寫法如下。 例:document.URL="http://www.google.com"; 注意:改變document.URL來實現導航的方法在新式瀏覽器中皆不適用,因此不要使用此屬性,請改用location物件來處理。 |
vlinkColor | 屬性 | |
close() | 方法 | |
createAttribute() | 方法 | 原文:Creates a new attribute, ready to be inserted somewhere in the document. It returns a reference to the created attribute. 語法:createAttribute("attributename") Example: var styleattr=document.createAttribute("align"); styleattr.nodeValue="center"; document.getElementById("sister").setAttributeNode(styleattr); |
createComment() | 方法 | 原文:Creates an instance of the comment node. Once created, you can then insert it into the document tree using appendChild(), for example. 語法:createComment(commenttext) Example: var commentnode=document.createComment("Copyright JavaScript Kit"); document.getElementById("mydiv").appendChild(commentnode); |
createDocumentFragment() | 方法 | 建立文件檔碎片節點。通常將節點新增到實際頁面中時,頁面就會立即更新並反映這個變化。對於少量的更新是非常實用的,而一旦新增的節點非常多時,頁面執行的效能就會降低。 通常解決辦法是使用createDocumentFragment()建立一個文件檔碎片,把新的節點先新增到該碎片上,然後再一次性新增到實際的頁面中,如下例: var myArray = ["太空戰士10","太空戰士7","DQ3","DQ8","街","太空戰士4","皇家騎士團2","太空戰士3","DQ7","薩爾達傳說時之笛","DQ5","天外魔境II","櫻花大戰","DQ4","太空戰士5","異域神兵","DQ2","櫻花大戰3","王國之心","快打旋風2","超級瑪莉兄弟","太空戰士8"]; var myBody = document.getElementsByTagName("body")[0]; var myFragment = document.createDocumentFragment(); for(var i=0; i<myArray.length; i++){ var myDiv = document.createElement("div"); var myText = document.createTextNode(myArray[i]); myDiv.appendChild(myText); myFragment.appendChild(myDiv); } myBody.appendChild(myFragment);原文:Creates an empty document fragment. The result is a temporary container for creating and modifying new elements or attributes before introducing the final result to your document tree. This is a very useful method when you're performing multiple operations that add to or modify the document tree. Instead of directly modifying the document tree each time (very inefficient), it's much better to use a temporary "whiteboard" that is created by createDocumentFragment() to perform all your operations on first before finally inserting the result to the document tree. For example: <div id="sister"></div> <script type="text/javascript"> var docfrag=document.createDocumentFragment(); var mydiv=document.createElement("div"); var divtext=document.createTextNode("This is div text"); mydiv.appendChild(divtext); docfrag.appendChild(mydiv); document.getElementById("sister").appendChild(docfrag) //div now reads "this is div text"; </script> |
createElement() | 方法 | 建立元素節點;document物件,要寫成document.createElement();可以配合appendChild()等的DOM方法將新建立的節點插入文件內,如下例將在<body>中插入一個<P>:var myBody = document.getElementsByTagName("body"); var newObj = document.createElement("p"); //先將建立好的<P>存到一個變數中 myBody[0].appendChild(newObj);範例2: var textblock=document.createElement("p"); textblock.setAttribute("id", "george"); textblock.setAttribute("align", "center"); document.body.appendChild(textblock); |
createTextNode() | 方法 | 建立文字節點。 原文:Creates a new text node, which can then be added to an element in the document tree. For example: var headertext=document.createTextNode("Welcome to JavaScript Kit"); document.getElementById("mytitle").appendChild(headertext); |
elementFromPoint() | 方法 | 傳回指定座標上的一個元素。 語法:elementFromPoint(x,y) 上述之座標是由瀏覽器內window元素的左上角算起,超出此範圍皆不成立,例如座標值設為負值或超出視窗可視範圍;另外如果指定的座標上有一個以上的元素,此方法會傳回符合座標中z-index最上層的元素,如下例點擊連結後alert將傳回div2,並且div2底色改為紅色: <a href="javascript:;">改變座標位於x220,y220之元素的底色</a> <div style="position:absolute; left:180px; top:180px; background:green; width:200px; height:200px;">div1</div> <div style="position:absolute; left:190px; top:190px; background:blue; width:200px; height:200px;">div2</div> <script> document.getElementsByTagName('a')[0].onclick = function(){ var po=document.elementFromPoint(220, 220); po.style.background='red'; alert(po.innerText); } </script>網路上某些文章表示Google Chrome不支援此方法(包括下列原文的Javascript Kit說明也是),但實測後是可執行的,可能是新版Chrome把它加入了吧。 原文:Supported in IE, FF3+, and Opera9+ Returns the element at the designated coordinates relative to the upper left corner of the browser window's viewport. As you scroll the document, the same coordinates (ie: x:20,y:20) may point to a different element as a result. The following displays in the browser's title bar the element the mouse is currently over: document.onmousemove=function(e){ var evt=window.event || e; var elfrompoint=document.elementFromPoint(evt.clientX, evt.clientY); document.title=elfrompoint.tagName; } |
getComputedStyle() | 方法 | 取得指定元素的風格表物件實際的CSS屬性值,不論他們是使用行內CSS設定,或是global/external stylesheets設定;IE不支援,IE使用currentStyle。 語法:window.getComputedStyle(元素物件, 假元素); 元素物件是 HTML 元素的物件。假元素是字串,一般元素設為 null。此方法傳回風格表物件。此法取得的風格表物件是唯讀的,如要更改元素的風格表,則要用 元素物件.style.特徵。 範例:document.write(getComputedStyle(mySpan,null).color); 原文:Firefox/W3C only method that returns a style object containing the actual CSS property values added to an element, whether they are set using inline CSS or global/external stylesheets. To get the value to a specific cascaded CSS property, you'd just look up that property within the returned object. Note that while window.getComputedStyle() is supported in Firefox, Safari only supports document.defaultView.getComputedStyle() (with Firefox supporting both methods). For maximum compatibility then, you should use the later method. The following example shows how to retrieve the value of the CSS property "padding", applied to the element via external style sheet: <head> <style type="text/css"> #adiv{padding: 10px;} </style> </head> <body> <div id="adiv">This is some text</div> <script type="text/javascript"> var mydiv=document.getElementById("adiv"); var actualstyle=document.defaultView.getComputedStyle(mydiv, ""); var divpadding=actualstyle.padding //contains "10px"; </script> </body> |
getElementById() | 方法 | document物件,要寫成document.getElementById();利用html中id名稱訪問某個指定元素;標準的html文件id都是唯一的,所以訪問的對像也只會有一個。 例如下例中的li指定了id,則可以直接訪問: var findID = document.getElementById("css"); alert(findID.tagName+" - "+findID.childNodes[0].nodeValue);} <ul> <li>HTML</li> <li>Javascript</li> <li id="css">CSS</li> </ul> <ul> <li>ASP</li> <li>JSP</li> <li>PHP</li> </ul>另外我們也可以指定一個document.getElementById()指定一個物件,再以getElementsByTagName()[n]來指定其中的某一個子元素,如下例: var links = document.getElementById("friedslink").getElementsByTagName("a")[0]; |
getElementsByClassName() | 方法 | 返回一組含有指定Class名稱的元素陣列,如下例:
document.getElementsByClassName("cats"); //取得有"cast" class name的元素集合如果某些元素有一個以上的class名稱,我們可以用空格將們隔開來選取這些元素,如下例: document.getElementsByClassName("animal cats"); //取得同時有"animal"和"cats" class name的元素集合我們也可以指定一個根元素,再取得該元素內的子元素,如下例: document.getElementsByTagName('ul')[0].getElementsByClassName('cat')[0];getElementsByClassName()只有到IE9才正式支援,IE9以下的版本只能用自定的函數來處理,下面列出一個網路上寫的非常好的範例: (function(){ if (!document.getElementsByClassName) { var indexOf = [].indexOf || function(prop) { for (var i = 0; i < this.length; i++) { if (this[i] === prop) return i; } return -1; }; getElementsByClassName = function(className,context) { var elems = document.querySelectorAll ? context.querySelectorAll("." + className) : (function() { var all = context.getElementsByTagName("*"), elements = [], i = 0; for (; i < all.length; i++) { if (all[i].className && (" " + all[i].className + " ").indexOf(" " + className + " ") > -1 && indexOf.call(elements,all[i]) === -1) elements.push(all[i]); } return elements; })(); return elems; }; document.getElementsByClassName = function(className) { return getElementsByClassName(className,document); }; Element.prototype.getElementsByClassName = function(className) { return getElementsByClassName(className,this); }; } })(); document.getElementsByClassName = function(eleClassName){ var getEleClass = [];//定義一個陣列 var myclass = new RegExp("\\b"+eleClassName+"\\b");//創建一個規則運算式對像 var elem = this.getElementsByTagName("*");//獲取文檔裡所有的元素 for(var h=0;h<elem.length;h++){ var classes = elem[h].className;//獲取class對像 if(myclass.test(classes)){ getEleClass.push(elem[h]);//正則比較,取到想要的CLASS對像 } } return getEleClass;//返回陣列 } |
getElementsByName() | 方法 | 原文:Returns an array of elements with a name attribute whose value matches that of the parameter's. In IE6, elements with an ID attribute of the matching value will also be included in the array, and getElementsByName() is limited to retrieving form objects such as checkboxes and INPUT. In Firefox, nither of these "pitfalls" apply.
<div name="george">f</div> <div name="george">f</div> <script type="text/javascript"> var georges=document.getElementsByName("george") for (i=0; i< georges.length; i++) // do something with each DIV tag with name="george". Firefox only. </script> |
getElementsByTagName() | 方法 | document物件,要寫成document.getElementsByTagName();利用標籤名取得元素物件的清單。 用來返回一個包含某個相同標籤名元素的NodeList;例如<img>標記的標籤名為img。 下列範例(1)返回文件中所有的<li>元素清單: var allLi = document.getElementsByTagName("li");要注意的是,文件檔的DOM結構必須在整個文件檔載入完成後才能正確分析出來,因此上例必須在頁面完全載入後才能生效,如範例(2)所示。 window.onload = function(){ allLi = document.getElementsByTagName("li"); alert(allLi.length+" - "+allLi[0].tagName+" - "+allLi[3].childNodes[0].nodeValue); } <ul> <li>HTML</li> <li>Javascript</li> <li>CSS</li> </ul> <ul> <li>ASP</li> <li>JSP</li> <li>PHP</li> </ul>原文:Returns an array of elements whose tag name matches the parameter. In Firefox/ IE6+, you may enter an asterisk ("*") as the parameter to retrieve a list of all elements within the document. var ptags=document.getElementsByTagName("p"); var alltags=document.getElementsByTagName("*"); //returns all elements on page |
open() | 方法 | |
querySelector() | 方法 |
回傳DOM tree中第一個符合指定CSS選擇器的元素,若找不到該元素就會回傳null(如此可以用來判斷頁面中有沒有某個元素) 語法:document.querySelector(selectors) 範例1,返回指定元素的html內容: <ul id="mylist"> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> </ul> <script type="text/javascript"> var item2=document.getElementById("mylist").querySelector('li:nth-of-type(2)') alert(item2.innerHTML) //"Item 2" </script>範例2, 使用逗號做分隔帶入串個CSS選擇器,例如: // html <p class="">這是段落</p> <p class="ele2">這是段落</p> <p class="ele3">這是段落</p> // javascript var myEle = document.querySelector('.ele1, .ele2');上例html中並沒有ele1這個class,所以第一個符合的元素為ele2。 範例3,在Dom元素上使用querySelector(): document.querySelector('.outer').querySelector('.inner:nth-child(2)').classList.add('myclass');上例基本上等於: document.querySelector('.outer .inner:nth-child(2)').classList.add('myclass'); |
querySelectorAll() | 方法 |
回傳DOM tree中所有符合指定CSS選擇器的NodeList(節點的集合),找不到符合的選擇器就傳回空陣列(如此可以用陣列的length來判斷頁面中有沒有某個元素) 語法:document.querySelectorAll(selectors) 範例1,選擇所有li元素: // HTML <ul> <li>Item 1</li> <li>Item 2</li> </ul> // javascript var listItem = document.querySelectorAll('li'); for(var v of listItem){ alert(v.innerHTML); }範例2,我們可以像一般CSS選擇器以逗號分隔選擇多個元素: document.querySelectorAll("#div1, #div2")範例3,在Dom元素上使用querySelectorAll(): var childAry = document.querySelector('.outer').querySelectorAll('.inner');上例基本上等於: var childAry = document.querySelectorAll('.outer .inner'); |
write() | 方法 | 在html文件中插入內容,<script></script>寫在哪就插在哪,接受純文字或是html標籤。 要注意如果document.write()是被放在window.onload = function(){}的函數裡,在文件一載入時document.write()會把原本的的內容全部覆蓋掉。 個人認為這個方法在應用上滿雜亂的,下例列出大概會發生的情形: <html> <head> <title>HTML5</title> <script class="myScript"> document.write('<script src="test.js"><\/script>'); //在「.myScript」後被插入,並且script的內容會被執行 document.write('<h1>在<body>開頭插入</h1>'); </script> </head> <body> <p>這是原本的內容</p> <p>這是原本的內容</p> <p>這是原本的內容</p> <p>這是原本的內容</p> <script> document.write('<h1>在<body>結尾插入</h1>'); /*window.onload = function(){ document.write('我會蓋掉所有<body>內的內容'); }*/ </script> </body> </html> |
writeln() | 方法 |