首頁  >  文章  >  web前端  >  js基礎之DOM中document物件的常用屬性方法詳解

js基礎之DOM中document物件的常用屬性方法詳解

高洛峰
高洛峰原創
2016-12-08 14:35:351226瀏覽

-----引入

每個載入瀏覽器的 HTML 文件都會成為 Document 物件。

Document 物件使我們可以從腳本中對 HTML 頁面中的所有元素進行存取。

屬性

1  document.anchors  傳回文件中所有 Anchor 物件的引用。還有document.links/document.forms/document.images等

2  document.URL       傳回目前文件的url

3  document.ti    

方法

1  document.close()     關閉以document.open() 方法開啟的輸出流,並顯示選取的資料。

<!DOCTYPE html>
<html>
<head>
<script>
function createDoc()
{
var w=window.open();
w.document.open();
w.document.write("<h1>Hello World!</h1>");
w.document.close();
}
</script>
</head>
 
<body>
<input type="button" value="New document in a new window" onclick="createDoc()">
</body>
</html>

2  document.createElement()     建立元素節點。

<!DOCTYPE html>
<html>
<!DOCTYPE html>
<head>
</head>
<body>
  <p>hello world</p>
   
<script>
  var a = document.createElement(&#39;hr&#39;);
  document.body.appendChild(a)
 
 
</script>
</body>
</html>

3  document.createAttribute()   建立屬性節點。

<!DOCTYPE html>
<html>
<body>
 
<p id="demo">Click the button to make a BUTTON element.</p>
 
<button onclick="myFunction()">Try it</button>
 
<script>
 
function myFunction()
{
var btn=document.createElement("BUTTON");
document.body.appendChild(btn);
};
 
</script>
 
</body>
</html>

4  document.createTextNode()  建立文字節點。

<!DOCTYPE html>
<html>
<!DOCTYPE html>
<head>
</head>
<body>
  <p>hello world</p>
 
<script>
  var a = document.createTextNode(&#39;hahahah&#39;);
  document.body.appendChild(a)
 
 
</script>
</body>
</html>

5  document. getElementsByClassName()   傳回文件中所有指定類別名稱的元素集合,作為 NodeList 物件集合。所謂NodeList物件集合,是類似陣列的資料格式,僅僅提供了length屬性,像是陣列中的push  pop方法等都未提供。

6  document.getElementById() 傳回擁有指定 id 的第一個物件的參考。

7  document.getElementsByName() 傳回指定名稱的物件集合。

8  document.getElementsByTagName() 傳回指定標籤名的物件集合。

9  document.write() 寫 HTML 運算式 或 JavaScript 程式碼。注意:當html文檔載入完後再使用write方法,會導致write內容覆寫原本的html文檔。

<!DOCTYPE html>
<html>
<!DOCTYPE html>
<head>
</head>
<body>
  <p>hello world</p>
 
<script>
  document.write(&#39;hahahh&#39;)
 
 
</script>
</body>
</html>

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn