JavaScript setAttribute()方法
setAttribute() 方法用于设置或添加特定元素的属性,并为其提供一个值。如果该属性已经存在,则仅设置或更改属性的值。因此,我们还可以使用 setAttribute() 方法来更新现有属性的值。如果对应的属性不存在,它将创建一个具有指定名称和值的新属性。该方法不返回任何值。当我们在 HTML 元素上使用它时,属性名称会自动转换为小写。
虽然我们可以使用 setAttribute() 方法添加 style 属性,但不建议使用此方法进行样式设置。要添加样式,我们可以使用style对象的属性来有效地更改样式。以下代码可以清楚地说明。
错误的使用方式
不建议使用它来更改样式。
element.setAttribute("style", "background-color: blue;");
正确的方式
下面给出了改变样式的正确方式。
element.setAttribute.backgroundColor = "blue";
要获取属性的值,我们可以使用 getAttribute() 方法,要从元素中删除特定属性,我们可以使用 removeAtrribute() 方法。
如果我们要添加一个布尔属性,比如 disabled ,那么不管它的值是什么,它总是被认为是 true 。如果我们需要将布尔属性的值设置为 false ,我们必须使用 removeAttribute() 方法来删除整个属性。
语法
element.setAttribute(attributeName, attributeValue)
这个方法的参数是不可选的。使用这个方法时,两个参数都必须包含在内。这个方法的参数值定义如下。
参数值
attributeName: 它是我们想要添加到元素的属性的名称。它不能为空,即不可选。
attributeValue: 它是我们要添加到元素中的属性的值。它也不是可选值。
让我们通过一些示例来了解如何使用 setAttribute() 方法。
示例1
在这个示例中,我们将一个 href 属性添加到 < a>标签中,其值为 “https://www.javatpoint.com/” ,并赋予 id=”link” 。
<html>
<head>
<title> JavaScript setAttribute() method </title>
<script>
function fun() {
document.getElementById("link").setAttribute("href", "https://www.javatpoint.com/");
}
</script>
</head>
<body style = "text-align: center;">
<h2> It is an example of adding an attribute using the setAttribute() method. </h2>
<a id = "link"> javaTpoint.com </a>
<p> Click the follwing button to see the effect. </p>
<button onclick = "fun()"> Add attribute </button>
</body>
</html>
输出
在执行上述代码后,输出将会是 –
现在,我们可以看到链接已创建。
示例2
在此示例中,我们使用 setAttribute() 方法更新现有属性的值。在这里,我们通过将 type 属性的值从 text 更改为 button ,将文本框转换为按钮。
我们需要点击指定的按钮才能看到效果。
<html>
<head>
<title> JavaScript setAttribute() method </title>
<script>
function fun() {
document.getElementById("change").setAttribute("type", "button");
}
</script>
</head>
<body style = "text-align: center;">
<h2> It is an example to update an attribute's value using the setAttribute() method. </h2>
<input id = "change" type = "text" value = "javaTpoint"/>
<p> Click the follwing button to see the effect. </p>
<button onclick = "fun()"> Change </button>
</body>
</html>
输出
在执行以上代码后,输出将是 –
示例3
在这里,我们添加了一个布尔属性 disabled 来禁用指定的按钮。如果我们将 disabled 属性的值设置为空字符串,那么它会自动设置为true,导致按钮被禁用。
<html>
<head>
<title> JavaScript setAttribute() method </title>
<script>
function fun() {
document.getElementById("btn").setAttribute("disabled", "");
}
</script>
</head>
<body style = "text-align: center;">
<h2> Example of the setAttribute() method. </h2>
<p> Click the following button to see the effect </p>
<button onclick = "fun()" id = "btn"> Click me </button>
</body>
</html>
输出
在上述代码执行后,输出结果将会是 –
点击按钮后,将会显示以下结果 –