HTML DOM createAttribute() 方法

htmlweb developmentfront end technology更新于 2025/9/24 19:24:17

HTML DOM createAttribute() 方法用于使用 JavaScript 为 HTML 元素创建特定属性。createAttribute() 方法使用给定名称创建一个属性,并将该属性作为 Attr 对象返回。

语法

以下是 createAttribute() 方法的语法 −

document.createAttribute(attributename)

示例

让我们来看一个 HTML DOM createAttribute() 方法的示例 −

<!DOCTYPE html>
<html>
<head>
<title>CREATE ATTRIBUTE</title>
<style>
   #DIV1{
      margin-top:15px;
      width:250px;
      height:200px;
      border:2px solid blue;
      background-color:lightgreen;
   }
</style>
</head>
<body>
<p>Click the button to create a "class" attribute for the div element</p>
<button onclick="attrCreate()">CREATE</button>
<br>
<div>
<p>This is a sample div</p>
</div>
<script>
   function attrCreate() {
      var x = document.getElementsByTagName("div")[0];
      var att = document.createAttribute("id");
      att.value = "DIV1";
      x.setAttributeNode(att);
   }
</script>
</body>
</html>

输出

这将产生以下输出 −

点击"创建"按钮 −

在上面的例子中 −

我们创建了一个 id 为"DIV1"的样式

#DIV1{
   margin-top:15px;
   width:250px;
   height:200px;
   border:2px solid blue;
   background-color:lightgreen;
}

然后,我们创建了一个 <div> 元素,其中包含一个 <p> 元素。

<div>
<p>这是一个示例 div</p>
</div>

然后,我们创建了一个 CREATE 按钮,当用户点击该按钮时,它将执行 attrCreate() 函数 −

<button onclick="attrCreate()">CREATE</button>

attrCreate() 函数使用 document 对象上的 getElementsByTagName() 方法获取 <div> 元素,并将其赋值给变量 x。我们使用 createAttribute() 方法创建 “id”属性,并使用其 value 属性为其赋值"DIV1",这是我们之前创建的样式的 ID。最后,我们将"id"属性及其值一起设置为

元素 −

function attrCreate() {
   var x = document.getElementsByTagName("div")[0];
   var att = document.createAttribute("id");
   att.value = "DIV1";
   x.setAttributeNode(att);
}

相关文章


有用资源