document 節點對象,html
表明整個文檔,每張網頁都有本身的 document 對象。node
window.document 當瀏覽器開始加載文檔時就存在了數組
// 頁面滾動到瀏覽器頂部 document.scrollingElement.scrollTop = 0;
// 判斷 video 元素是否是全屏狀態 if (document.fullscreenElement.nodeName == 'VIDEO') { console.log('全屏播放視頻'); }
這些集合都是動態的,網頁節點發生任何變化,都會反映在這些集合中。瀏覽器
href
屬性的 <a> 及 <area> 節點// 打印文檔全部的連接 var links = document.links; for(var i = 0; i < links.length; i++) { console.log(links[i]); }
// http://www.example.com:80/hello.html document.domain; // www.example.com
// HTML 代碼以下 // <iframe id="editor" src="about:blank"></iframe> var editor = document.getElementById('editor'); editor.contentDocument.designMode = 'on';
var doc = document.implementation.createHTMLDocument('Title'); var p = doc.createElement('p'); p.innerHTML = 'hello world'; doc.body.appendChild(p); document.replaceChild( doc.documentElement, document.documentElement );
var element = document.elementFromPoint(50, 50);
var range = document.caretPositionFromPoint(clientX, clientY);
var div = document.createElement('div'); div.appendChild(document.createTextNode('<span>Foo & bar</span>')); console.log(div.innerHTML) // <span>Foo & bar</span>
var docfrag = document.createDocumentFragment(); [1, 2, 3, 4].forEach(function (e) { var li = document.createElement('li'); li.textContent = e; docfrag.appendChild(li); }); var element = document.getElementById('ul'); element.appendChild(docfrag);
上面代碼中,文檔片段docfrag包含四個<li>節點,這些子節點被一次性插入了當前文檔。cookie
var event = document.createEvent('Event'); event.initEvent('build', true, true); document.addEventListener('build', function (e) { console.log(e.type); // "build" }, false); document.dispatchEvent(event);
// 添加事件監聽函數 document.addEventListener('click', listener, false); // 移除事件監聽函數 document.removeEventListener('click', listener, false); // 觸發事件 var event = new Event('click'); document.dispatchEvent(event);
var iframe = document.getElementsByTagName('iframe')[0]; var oldNode = iframe.contentWindow.document.getElementById('myNode'); var newNode = document.importNode(oldNode, true); document.getElementById("container").appendChild(newNode);
上面代碼從 iframe 窗口,拷貝一個指定節點 myNode,插入當前文檔app