📜  JavaScript setAttribute()

📅  最后修改于: 2020-10-27 00:57:38             🧑  作者: Mango

JavaScript setAttribute()

setAttribute()方法用于将属性设置或添加到特定元素,并为其提供值。如果属性已经存在,则仅设置或更改属性的值。因此,我们还可以使用setAttribute()方法来更新现有属性的值。如果相应的属性不存在,它将创建具有指定名称和值的新属性。此方法不返回任何值。当我们在HTML元素上使用属性名称时,属性名称会自动转换为小写。

尽管我们可以使用setAttribute()方法添加样式属性,但是建议不要使用此方法进行样式设置。为了添加样式,我们可以使用样式对象的属性来有效地更改样式。用下面的代码可以很清楚。

方式错误

建议不要使用它来更改样式。

element.setAttribute("style", "background-color: blue;");

正确的方法

下面给出了更改样式的正确方法。

element.setAttribute.backgroundColor = "blue";

要获取属性的值,我们可以使用getAttribute()方法,而要从元素中删除特定属性,可以使用removeAtrribute()方法。

如果我们要添加布尔值属性(例如Disabled),则无论其具有什么值,始终将其视为true。如果需要将Boolean属性的值设置为false,则必须使用removeAttribute()方法删除整个属性。

句法

element.setAttribute(attributeName, attributeValue)

此方法的参数不是可选的。使用此方法时,必须同时包含两个参数。该方法的参数值定义如下。

参数值

attributeName:这是我们要添加到元素的属性的名称。它不能为空。即,它不是可选的。

attributeValue:这是我们要添加到元素的属性的值。它也不是可选值。

让我们通过一些插图来了解如何使用setAttribute()方法。

例1

在此示例中,我们向id =“ link”的标签添加了值为“ https://www.javatpoint.com/”的href属性。



 JavaScript setAttribute() method 




It is an example of adding an attribute using the setAttribute() method.

javaTpoint.com

Click the follwing button to see the effect.

输出量

执行完上述代码后,输出将为-

我们可以看到,在单击给定按钮之前,未创建链接。单击按钮后,输出将为-

现在,我们可以看到链接已创建。

例2

在此示例中,我们将使用setAttribute()方法更新现有属性的值。在这里,我们通过将类型属性的值从文本更改为按钮来将文本字段转换为按钮。

我们必须单击指定的按钮才能看到效果。



 JavaScript setAttribute() method 




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

Click the follwing button to see the effect.

输出量

执行完上述代码后,输出将为-

单击按钮后,输出将为-

例子3

在这里,我们添加了一个布尔属性,该属性被禁用以禁用指定的按钮。如果我们将Disabled属性的值设置为空字符串,那么它将自动设置为true,这将导致按钮被禁用。

   
   
       JavaScript setAttribute() method 
      
   
   
   
   

Example of the setAttribute() method.

Click the following button to see the effect

输出量

执行完上述代码后,输出将为-

单击按钮后,输出将为-