我想更改
<td rowspan="2"><img src="/ORegMx/capito.png" alt="capito"></td>
对此
<td rowspan="2"><div id="divPage"><img src="/ORegMx/capito.png" alt="capito"></div></td>
我尝试过
var elem = document.createElement("div");
elem.setAttribute("id", "divPage");
document.querySelector("body > table.troisbords > tbody > tr > td > table > tbody > tr > td > div > blockquote > table > tbody > tr:nth-child(2) > td > form > table > tbody > tr:nth-child(4) > td:nth-child(2) > img").appendChild(elem);
但它给出了
也尝试过
var str = '<div id="divPage"><img src="/ORegMx/capito.png"/></div>';
document.querySelector("body > table.troisbords > tbody > tr > td > table > tbody > tr > td > div > blockquote > table > tbody > tr:nth-child(2) > td > form > table > tbody > tr:nth-child(4) > td:nth-child(2)").replaceWith(str);
但它给出了
感谢任何帮助!
答案 0 :(得分:1)
您的代码尝试将div
放入 img
,但是您说过想让div
包装 >图片。为此,您需要:
将div添加到img
之前(或之后)的img
的父级,然后
将img
移至div
例如:
var div = document.createElement("div");
div.id = "divPage";
var img = document.querySelector("body > table.troisbords > tbody > tr > td > table > tbody > tr > td > div > blockquote > table > tbody > tr:nth-child(2) > td > form > table > tbody > tr:nth-child(4) > td:nth-child(2) > img");
var parent = img.parentNode;
var next = img.nextSibling;
div.appendChild(img);
parent.insertBefore(div, next);
将img
附加到div
时,它被移动(未复制)。
(还请注意,您可以将反射属性用于id
,不需要setAttribute
。)
实时示例:
var div = document.createElement("div");
div.id = "divPage";
var img = document.querySelector("#the-img");
var parent = img.parentNode;
var next = img.nextSibling;
div.appendChild(img);
parent.insertBefore(div, next);
#divPage {
border: 1px solid black;
}
<img id="the-img" src="https://via.placeholder.com/100x100.png?text=The%20Image">