javascript 动态添加dom元素,添加类名,添加自定义属性,添加点击事件,

//获取父节点

let farther =document.getElementById("farther")
//跟换属性值 假如跟换src的属性值
farther.src = 'image.jpg'

//创建节点
let son = document.createElement('div')

//为子节点更换类名/添加类名
son.className = 'newClassValue'

//为字节点添加自定义 属性名和值
son.setAttribute('myAttribute','myAttributeValue')

//为子节点添加点击事件
son.onclick = myfun

//向父元素 添加子节点,注意不要加引号""
farther.appendChild( son ) //添加新元素到尾部。
farther.insertBefore( son ) //添加新元素到开始位置

//获取自定义属性的值
let son = document.getElementById('son').getAttribute('myAttribute')

window.open('rul')  // 打开新窗口
window.close()      //关闭当前窗口

动态添加节点、

let father = document.getElementById('father')
for(let i=0;i<4;i++){
    let child = document.createElement('div')
    chile.onclick = myfun
    father.appendChild(child)
}

//最后这个father的父元素就有了 4个子节点,可以根据后台返回的数据进行动态添加

  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值