温馨提示×

JavaScript中setAttribute用法介绍

小云
106
2023-08-09 14:30:46
栏目: 编程语言

JavaScript中的setAttribute()方法用于设置指定元素的属性值。

语法:

element.setAttribute(attributeName, attributeValue)

参数说明:

  • attributeName:要设置的属性名称,必选。

  • attributeValue:要设置的属性值,必选。

注意事项:

  • 如果指定的属性不存在,则setAttribute()方法将创建该属性并设置属性值。

  • 如果指定的属性已经存在,则setAttribute()方法将覆盖原有的属性值。

  • 如果属性名称或属性值为空字符串,setAttribute()方法将抛出错误。

  • 如果属性名称包含非法字符或属性值包含特殊字符,setAttribute()方法将自动进行转义处理。

示例:

var element = document.getElementById("myElement");
element.setAttribute("class", "highlight");
// 设置data属性
element.setAttribute("data-id", 123);
// 设置自定义属性
element.setAttribute("myAttr", "myValue");

在上述示例中,首先通过getElementById()方法获取了id为"myElement"的元素,然后使用setAttribute()方法为该元素设置了class属性的值为"highlight"。接下来,又使用setAttribute()方法为该元素设置了data-id属性和myAttr属性,并分别设置了对应的属性值。

0