繁体   English   中英

通过父 class 定位所有链接,将“rel”属性添加到链接(不带 jQuery)

[英]Target all link by parent class, add "rel" attribute to link (without jQuery)

我有这个 Codepen 演示如何使用 jQuery 来做到这一点 我试图用香草 Javascript 来做,但无法让它工作。 在普通的 ES6 中,你会如何 go?

HTML:

<div class="external">
  <figure>
    <a href="https://via.placeholder.com/150" target="_blank">
      <img src="https://via.placeholder.com/150" class="vc_single_image-wrapper" width="150" height="150">
    </a>
    </figure>
</div>
<div class="external">
  <figure>
    <a href="https://via.placeholder.com/150" target="_blank">
      <img src="https://via.placeholder.com/150" class="vc_single_image-wrapper" width="150" height="150">
    </a>
    </figure>
</div>
<p>Placeholder images courtesty of <a href="https://placeholder.com" target="_blank" rel="noopener noreferrer">Placeholder.com</a></p>

Javascript:

$(document).ready(function () {
  // Scan the webpage for all class names of 'external'.
  $(".external").each(function () {
    // For each class name of 'external' found, find descendant tag "a" of that div and apply the rel attribute.
    $(".external a").attr("rel", "external noopener");
  });
});

您可以只做document.querySelectorAll('.external a').forEach来遍历所有这些:

 document.querySelectorAll('.external a').forEach((el) => { el.setAttribute('rel', 'external noopener'); });
 <div class="external"> <figure> <a href="https://via.placeholder.com/150" target="_blank"> <img src="https://via.placeholder.com/150" class="vc_single_image-wrapper" width="150" height="150"> </a> </figure> </div> <div class="external"> <figure> <a href="https://via.placeholder.com/150" target="_blank"> <img src="https://via.placeholder.com/150" class="vc_single_image-wrapper" width="150" height="150"> </a> </figure> </div> <p>Placeholder images courtesty of <a href="https://placeholder.com" target="_blank" rel="noopener noreferrer">Placeholder.com</a></p>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM