欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

js常用DOM方法詳解

 更新時間:2017年02月04日 15:38:13   作者:libra天秤  
本文主要介紹了js常用的DOM方法,具有很好的參考價值,下面跟著小編一起來看下吧

介紹幾個js DOM的常用方法

獲取元素節(jié)點 getElementById    getElementsByTagName    getElementsByClassName

先寫一個簡單的網(wǎng)頁做測試:

/*
  test.html
*/
<!DOCTYPE html>
<html>
<head>
 <meta charset="utf-8">
 <title>test</title>
</head>
<body>
 <p id="contentId" style="width:500px; height: 30px;background-color: #ccc">這段的id是contentId。</p>
 <p class="contentClass" style="width:500px; height: 30px;background-color: #ccc">這段的class name是contentClass。</p>
</body>
</html>

1.  getElementById 

 1.先定義變量 var contentId = document.getElementById("contentId");

 2.然后輸出對象 contentId 就返回id為 contentId  的元素對象( <p id="contentId" style="width:500px; height: 30px;background-color: #ccc"> )。見下圖:

2.  getElementsByTagName  

   1.還是先定義變量  var contentTag = document.getElementsByTagName("p"); 

 2.接著我輸出 contentTag ,它返回 HTMLCollection [ <p#contentId>, <p.contentClass> ] 共兩個,一個以#開頭表示id,另一個以.開頭表示Class name。

 3.繼續(xù) contentTag[0]  輸出 <p id="contentId" style="width:500px; height: 30px;background-color: #ccc">

 contentTag[1] 輸出 <p class="contentClass" style="width:500px; height: 30px;background-color: #ccc">

由此可知 getElementsByTagName   返回的是數(shù)組!

3.  getElementsByClassName 

  1. var contentClass = document.getElementsByClassName("contentClass");

  2. contentClass 輸出 HTMLCollection [ <p.contentClass> ] 返回一個元素對象數(shù)組,即使只有一個。

  3. contentClass[0] 輸出 <p class="contentClass" style="width:500px; height: 30px;background-color: #ccc">

我們常用的還有 getAttribute,setAttribute,ChildNodes, nodeType, nodeValue, firstChild, lastChild 方法獲取一些信息。

4.分別用 getAttribute 和 setAttribute 獲取和設(shè)置屬性:

改變style屬性后:

5.那么這是childNOdes:

也就是說, <p></p> 在遇到塊元素時,塊元素之間會有一個換行符 <br> ,瀏覽器在查找子節(jié)點時會將它視為一個文本節(jié)點。從圖中也可以看出 childNodes 返回的也是數(shù)組。

那如果是<p#contentId>呢?

nodeType 的值有12種,常用的也就三種:1表示元素節(jié)點,2表示屬性節(jié)點,3表示文本節(jié)點。

nodeValue 不僅可以獲取文本節(jié)點的值,還可以改變文本節(jié)點的值。

js的dom方法還有好多,可以看看這個W3school JS參考手冊,相信對初學(xué)者有很大幫助。

以上就是本文的全部內(nèi)容,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,同時也希望多多支持腳本之家!

相關(guān)文章

最新評論