JS原生操作DOM(更新中)

在React项目中有时需要原生的JS操作DOM(项目没有引用jquery库),这里持续更新一些方法:

一、父子节点中插入中间层(div等)

最近在做一个需求,一个后端返回的html代码中给图片加“查看原图”按钮,由于需要基于父元素定位,所以要用div将原有的img包起来,并且在img后加入input标签,需要用到插入中间层的功能。

思路:通过img获取到父元素,在父元素中添加新的div子元素,然后将img添加入新div中…

此处注意到一个问题:子元素需不需要先从旧的父中移除再添加进新的父中呢?
MDN:The Node.insertBefore() method inserts a node before the reference node as a child of a specified parent node. If the given child is a reference to an existing node in the document, insertBefore() moves it from its current position to the new position (there is no requirement to remove the node from its parent node before appending it to some other node).

意思是Node.insertBefore()函数为我们实现了“已有节点移除并添加”的功能,所以父子节点中插入中间层代码:

// 添加查看原图按钮
let grands = document.getElementsByClassName("item-detail");
for(let i=
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值