我有一些 div
拥有相同的 className (.sampleClass)
其中包含 a
和 img
元素。我设法将 href
值从 a
继承到 img
,但是,由于这些元素驻留在 divs
中使用相同的 className
,href
继承应用于所有 img
元素,仅使用 href
值 a
在 div
中用 .sampleClass
标识。
JavaScript 之前的 HTML:
<div class="sampleClass">
<h2><a href="example.html">text</a></h2>
<img src="./img/someImg.png" />
<p>text</p>
<a><span>text</span></a>
</div>
<div class="sampleClass">
<h2><a href="random.html">text</a></h2>
<img src="./img/someOtherImg.png" />
<p>text</p>
<a><span>text</span></a>
</div>
使用了以下 JavaScript(vanilla):
var aHref = document.querySelector(".sampleClass > a").getAttribute("href");
var img = document.querySelectorAll("img"); /* or (".sampleClass > img") */
img.forEach(function(inheritHrefImg) {
inheritHrefImg.setAttribute("href", aHref);
})
JavaScript 之后的 HTML:
<div class="sampleClass">
<h2><a href="example.html">text</a></h2>
<img src="./img/someImg.png" href="example.html" /> /* this is correct */
<p>text</p>
<a><span>text</span></a>
</div>
<div class="sampleClass">
<h2><a href="random.html">text</a></h2>
<img src="./img/someOtherImg.png" href="example.html" /> /* want href to be "random.html" */
<p>text</p>
<a><span>text</span></a>
</div>
我需要一种方法来指示 img
元素仅针对 div
中 a
元素的 href
> img
和 a
都在其中。
提前致谢!
注意:不幸的是,给每个 div
一个单独的 className
,虽然是一个解决方案,但不是一个选项。
最佳答案
只需遍历 div
相反。另请注意,您的示例缺少第一个 </div>
结束标记,我想:
document.querySelectorAll('.sampleClass')
.forEach(sampleClass => {
sampleClass.children[1].setAttribute('href', sampleClass.children[0].children[0].getAttribute('href'));
});
console.log(document.body.innerHTML);
<div class="sampleClass">
<h2><a href="example.html">text</a></h2>
<img src="./img/someImg.png" />
</div>
<div class="sampleClass">
<h2><a href="random.html">text</a></h2>
<img src="./img/someOtherImg.png" />
</div>
但是img
s 不应该有 href
s,我不知道那应该做什么;将它们简单地包含在另一个动态创建的 a
中会更加优雅,像这样:
document.querySelectorAll('.sampleClass')
.forEach(sampleClass => {
const { href } = sampleClass.children[0].children[0];
const img = sampleClass.children[1];
img.remove();
const newA = document.createElement('a');
newA.href = href;
newA.appendChild(img);
const newAinsert = sampleClass.insertBefore(newA, sampleClass.children[1]);
});
console.log(document.body.innerHTML);
<div class="sampleClass">
<h2><a href="example.html">text</a></h2>
<img src="./img/someImg.png" />
<p>text</p>
<span>text</span>
</div>
<div class="sampleClass">
<h2><a href="random.html">text</a></h2>
<img src="./img/someOtherImg.png" />
<p>text</p>
<span>text</span>
</div>
关于javascript - 使用 Vanilla JavaScript 将 href 目标从 <a> 继承到 <img> 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50014535/