Say you have an element, which you selected using querySelector():
假设您有一个使用querySelector()选择的元素:
const button = document.querySelector('#mybutton')
You can attach an attribute to it following those steps:
您可以按照以下步骤将属性附加到该属性:
- create the attribute 创建属性
- set its value 设定其价值
- attach the attribute to the element 将属性附加到元素
Example:
例:
const attribute = document.createAttribute('id')
attribute.value = `remove-${item.name}`
button.setAttributeNode(attribute)
If the element does not exist yet, you have to first create it, then create the attribute, then add the attribute to the element, and finally add the element to the DOM:
如果元素尚不存在,则必须首先创建它,然后创建属性,然后将属性添加到元素,最后将元素添加到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)