HTML DOM className 属性

htmlweb developmentfront end technology更新于 2025/9/23 5:00:17

HTML DOM className 属性用于为 HTML 元素分配 CSS 类。className 属性用于设置或返回元素的类名属性值。如果 HTML 元素没有关联的类,则返回空字符串。我们可以使用此属性 − 更改元素包含的类名。

语法

以下是语法 −

设置 className 属性 −

HTMLElementObject.className = class;

此处,class 值用于指定元素的类名。一个元素可以关联多个类,并用空格分隔。

示例

让我们看一个 HTML DOM className 属性的示例 −

<!DOCTYPE html>
<html>
<head>
<style>
   .firstDiv {
      width: 300px;
      height: 100px;
      background-color:lightgreen;
   }
   .secondDiv{
      color: red;
      border:solid 1px blue;
      margin-bottom:9px;
   }
</style>
</head>
<body>
<p>Click the below button to display the class attribute value of the div </p>
<div id="myDIV" class="firstDiv secondDiv">
This is a sample div element.
</div>
<button onclick="getClassName()">GET CLASS</button>
<p id="Sample"></p>
<script>
   function getClassName() {
      var x = document.getElementById("myDIV").className;
      document.getElementById("Sample").innerHTML ="The classNames with the div element
         are "+x;
   }
</script>
</body>
</html>

输出

这将产生以下输出 −

点击"获取类"按钮 −

在上面的例子中 −

我们创建了一个 id 为 “myDIV” 的 div,其中包含一些文本 −

<div id="myDIV" class="firstDiv secondDiv">
这是一个示例 div 元素。
</div>

然后,我们创建了一个按钮"GET CLASS",当点击 − 时,它将执行 getClassName() 方法。

<button onclick="getClassName()">GET CLASS</button>

getClassName() 方法将使用 getElementById() 方法获取 <div> 元素,并使用 <div> 元素上的 className 属性获取其所有类名,并将其赋值给变量 x。然后,类名将显示在 ID 为"Sample"的段落中 −

function getClassName() {
   var x = document.getElementById("myDIV").className;
   document.getElementById("Sample").innerHTML ="The classNames with the div element are "+x;
}

相关文章


有用资源