使用纯JavaScript将<a>标签的href目标继承到<img>标签中

3
我有一些拥有相同className(.sampleClass)的div,其中包含a和img元素。我成功地将href值从a继承到img,但由于这些元素位于具有相同className的div内,因此仅使用在.className div内找到的第一个a标签的href值将href继承应用于所有img元素。
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(原生)被使用:
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>

我需要一种方法来指示只针对包含 imga 元素的 div 内的 a 元素的 href 进行操作。

提前感谢!

注意:不幸的是,为每个 div 分配单独的 className,虽然是一种解决方案,但不可行。

2个回答

3
只需循环遍历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>

但是不应该有href属性,我不知道那是什么意思;更加优雅的方式是将它们放在另一个动态创建的标签中,就像这样:

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>


谢谢您提供的替代方法,我已经尝试了,但是<img>标签被发送到了最后一个位置。这是我的错,因为我没有提到在<img>标签之后还有其他不必要的元素。我已经将它们编辑到我的问题中了。 - KAindex


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接