在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=