我有一些拥有相同className(.sampleClass)的div,其中包含a和img元素。我成功地将href值从a继承到img,但由于这些元素位于具有相同className的div内,因此仅使用在.className div内找到的第一个a标签的href值将href继承应用于所有img元素。
JavaScript前的HTML:
以下 JavaScript(原生)被使用:
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>
我需要一种方法来指示只针对包含 img
和 a
元素的 div
内的 a
元素的 href
进行操作。
提前感谢!
注意:不幸的是,为每个 div
分配单独的 className
,虽然是一种解决方案,但不可行。