使用javasript用<div>包裹<img>

时间:2019-07-28 17:47:15

标签: javascript html

我想更改

<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);

但它给出了

enter image description here

也尝试过

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);

但它给出了

enter image description here

感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

您的代码尝试将div 放入 img,但是您说过想让div包装 >图片。为此,您需要:

  1. 将div添加到img之前(或之后)的img的父级,然后

  2. 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">