當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


HTML DOM getElementsByClassName()用法及代碼示例

HTML DOM getElementsByClassName() 方法用於獲取文檔中具有給定類名的所有元素的集合。它將所有給定元素作為 NodeList 對象返回。您可以使用索引號訪問返回對象中的任何元素。可以在任何單個元素上調用此方法,使其後代元素具有給定的類名。

用法

以下是 getElementsByClassName() 方法的語法 -

document.getElementsByClassName(classname)

在這裏,類名是字符串類型,表示要訪問的元素的類名。也可以通過用空格分隔來搜索多個類名。

示例

讓我們看一個 getElementsByClassName() 方法的例子 -

<!DOCTYPE html>
<html>
<head>
<script>
   function changePara() {
      var p = document.getElementsByClassName("PARA1");
      p[0].innerHTML = "This text has been changed";
      p[1].style.color = "red";
      p[1].style.backgroundColor = "yellow";
   }
</script>
</head>
<body>
<h1>getElementsByClassName() example</h1>
<p class="PARA1">Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua</p>
<p class="PARA1"> Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat</p>
<button onclick="changePara()">CHANGE</button>
</body>
</html>

輸出

這將產生以下輸出 -

單擊更改按鈕 -

在上麵的例子中 -

我們創建了兩個與它們關聯的 classname="PARA1" 的段落。

<p class="PARA1">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua</p>

<p class="PARA1"> Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat</p>

然後我們創建了一個按鈕 CHANGE,它將在用戶單擊時執行 changePara() -

<button onclick="changePara()">CHANGE</button>

changePara() 方法在文檔對象上使用 getElementsByClassName() 方法將 <p> 元素作為 nodeListObject 獲取,並將其分配給變量 p。我們使用索引號更改第一段的文本並對第二段應用一些樣式 -

function changePara() {
   var p = document.getElementsByClassName("PARA1");
   p[0].innerHTML = "This text has been changed";
   p[1].style.color = "red";
   p[1].style.backgroundColor = "yellow";
}

相關用法


注:本文由純淨天空篩選整理自AmitDiwan大神的英文原創作品 HTML DOM getElementsByClassName() method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。