Javascript教程
JavaScript基础
JavaScript Objects
JavaScript BOM
JavaScript DOM
JavaScript OOP
JavaScript Cookies
JavaScript事件
JavaScript异常
JavaScript常用

JS setAttribute()

setAttribute()方法用于为特定元素设置或添加属性,并为其提供值。如果属性已经存在,则仅设置或更改属性的值。因此,我们还可以使用 setAttribute()方法来更新现有属性的值。如果相应的属性不存在,它将创建具有指定名称和值的新属性。此方法不返回任何值。当我们在 HTML 元素上使用属性名称时,该属性名称会自动转换为小写。
尽管我们可以使用 setAttribute()方法添加 style 属性,但是建议不要使用此方法进行样式设置。为了添加样式,我们可以使用样式对象的属性来有效地更改样式。使用以下代码可以很清楚。
错误的方式
建议不要使用它来更改样式。
element.setAttribute("style", "background-color: blue;");
正确的方法
下面给出了更改样式的正确方法。
element.setAttribute.backgroundColor = "blue";
要获取属性的值,可以使用 getAttribute()方法,而要从元素中删除特定属性,可以使用 removeAtrribute()方法。
如果我们要添加布尔属性(如 disabled ),则无论其具有什么值,它始终被视为 true 。如果我们需要将布尔属性的值设置为 false ,则必须使用 removeAttribute()方法。

语法

element.setAttribute(attributeName, attributeValue)
此方法的参数不是可选的。使用此方法时,必须同时包含两个参数。此方法的参数值定义如下。

参数值

attributeName:这是我们所需要的属性名称想要添加到元素。它不能为空。也就是说,它不是可选的。
attributeValue:这是我们要添加到元素中的属性的值。它也不是可选值。
通过一些说明让我们了解如何使用 setAttribute()方法。

Example1

在此示例中,我们添加了一个 href 属性,该属性的值为 " https://www.lidihuo.com/" 标记和 id =" link"
<html>
<head>
<title> JavaScript setAttribute() method </title>
<script>
function fun() {
document.getElementById("link").setAttribute("href", "https://www.lidihuo.com/");
}
</script>
</head>
<body style = "text-align: center;">
<p> It is an example of adding an attribute using the setAttribute() method. </p>
<a id = "link"> lidihuo.com </a>
<p> Click the follwing button to see the effect. </p>
<button onclick = "fun()"> Add attribute </button>
</body>
</html>
输出
执行上述代码后,输出将为-
 JavaScript setAttribute()
我们可以看到,在单击给定按钮之前,未创建链接。单击按钮后,输出将是-
 JavaScript setAttribute()
现在,我们可以看到

Example2

在此示例中,我们使用 setAttribute()方法更新现有属性的值。在这里,我们通过将 type 属性的值从 text 更改为 button ,将文本字段转换为按钮。
我们必须单击指定的按钮才能看到效果。
<html>
<head>
<title> JavaScript setAttribute() method </title>
<script>
function fun() {
document.getElementById("change").setAttribute("type", "button");
}
</script>
</head>
<body>
<p> It is an example to update an attribute's value using the setAttribute() method. </p>
<input id = "change" type = "text" value = "lidihuo"/>
<p> Click the follwing button to see the effect. </p>
<button onclick = "fun()"> Change </button>
</body>
</html>
输出

Example3

此处,我们添加了布尔属性 disabled 来禁用指定的按钮。如果我们将 disabled 属性的值设置为空字符串,那么它将自动设置为true,这将导致按钮被禁用。
<html>
   <head>
      <title> JavaScript setAttribute() method </title>
      <script>
    function fun() {
       document.getElementById("btn").setAttribute("disabled", "");
    }
      </script>
   </head>
   <body>
   <p> Example of the setAttribute() method. </p>
   <p> Click the following button to see the effect </p>
<button onclick = "fun()" id = "btn"> Click me </button>
   </body>
</html>
输出

It is an example to update an attribute's value using the setAttribute() method.

Click the follwing button to see the effect.

昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4