`setAttribute()` 方法用于設(shè)置指定元素的屬性值。通過該方法,你可以動態(tài)地修改 HTML 元素的屬性。
`setAttribute()` 方法接受兩個參數(shù),第一個參數(shù)是要設(shè)置的屬性名稱,第二個參數(shù)是屬性的值。
下面是 `setAttribute()` 方法的語法示例:
element.setAttribute(name, value);
其中,`element` 是要設(shè)置屬性的元素,`name` 是屬性名稱,`value` 是屬性的值。
以下是一些示例用法:
// 設(shè)置元素的 id 屬性
var element = document.getElementById("myElement");
element.setAttribute("id", "newId");
// 設(shè)置元素的樣式屬性
element.setAttribute("style", "color: red; font-size: 16px;");
// 設(shè)置元素的自定義屬性
element.setAttribute("data-custom", "some value");
通過調(diào)用 `setAttribute()` 方法,你可以在 JavaScript 中動態(tài)地設(shè)置元素的屬性值,從而實現(xiàn)對元素的樣式、標(biāo)識或行為的修改。
需要注意的是,通過 `setAttribute()` 方法設(shè)置的屬性值會覆蓋原有的屬性值,如果該屬性不存在,則會創(chuàng)建該屬性。