在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; i<grands.length; i++){
let oImgs = grands[i].getElementsByTagName(\"img\");
for(let j=0; j<oImgs.length; j++){
let oDiv = document.createElement(\"div\");
let oBtn = document.createElement(\"input\");
oBtn.setAttribute(\'data-src\', oImgs[j].src);
oBtn.setAttribute(\'type\',\'button\');
oBtn.setAttribute(\'class\', \'seeBigPic\');
oBtn.setAttribute(\'value\', \'查看原图\');
// 通过img宽度设置按钮left
oBtn.setAttribute(\'style\', \'left:\' + (oImgs[j].width/2 - 39) + \'px\');
var p = oImgs[j].parentNode;
p.insertBefore(oDiv, oImgs[j]);
oDiv.appendChild(oImgs[j]);
oDiv.appendChild(oBtn);
oDiv.setAttribute(\'style\', \'position: relative\');
}
}
⚠️注意:
1、先获取img的父:Imgs[j].parentNode;
2、再在父中添加新div:p.insertBefore(oDiv, oImgs[j]);
3、再在新div中添加img:oDiv.appendChild(oImgs[j]);
如果先执行3,再执行2时,p中找不到img了。 (T T)
继续阅读与本文标签相同的文章
《算法技术手册》一3.5.1 算法名称和摘要
《算法技术手册》一3.5 算法举例
-
AI+5G科技创新 视频行业呈现轻应用化趋势
2026-05-14栏目: 教程
-
1.98亿滴滴用户添加了紧急联系人 每天百万个订单行程分享给亲友
2026-05-14栏目: 教程
-
工程院院士刘韵洁:5G前景很大,但主要是行业应用
2026-05-14栏目: 教程
-
陆奇:看好5G技术,但应用好5G还需要时间
2026-05-14栏目: 教程
-
在Visual Studio中使用clang-tidy进行代码分析
2026-05-14栏目: 教程
