如何使用原始Javascript创建HTML属性

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:

您可以按照以下步骤将属性附加到该属性:

  1. create the attribute

    创建属性
  2. set its value

    设定其价值
  3. 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)

翻译自: https://flaviocopes.com/how-to-create-attribute-dom/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值