如果你要在DOM中为一个HTML元素添加一个属性,使用vanilla JavaScript怎么办?
假设你有一个元素,你用querySelector()选择了它。
const button = document.querySelector('#mybutton')
你可以按照这些步骤给它附加一个属性。
- 创建属性
- 设置它的值
- 将属性附加到该元素上
例子。
const attribute = document.createAttribute('id')
attribute.value = `remove-${item.name}`
button.setAttributeNode(attribute)
如果该元素还不存在,你必须先创建它,然后创建属性,再将属性添加到元素上,最后将元素添加到DOM中。
const button = document.createElement('button')
const attribute = document.createAttribute('id')
attribute.value = `some-value`
button.setAttributeNode(attribute)
button.textContent = 'Click me'
document.querySelector('.container').appendChild(button)