代码点读机 / JavaScript / setAttribute

setAttribute JavaScript · 网页功能

为元素设置指定属性的值。

怎么用

元素.setAttribute("属性名", "值")

小例子

var a = document.getElementById("link");
a.setAttribute("href", "https://example.com");

页面效果

(属性被设置)

提醒:设置 data-* 属性后可用 dataset 读取。

官方文档:https://developer.mozilla.org/zh-CN/docs/Web/API/Element/setAttribute

在代码里遇到不认识的词?打开代码点读机,点一下就懂 → ← JavaScript全部词条