简体   繁体   English

通过 div id 选择 div 内的锚点

[英]Selecting anchors within div by div id

New to JS, just dipping in to solve a problem (I bet everyone says that.). JS 新手,只是想解决一个问题(我敢打赌每个人都这么说。)。 I need to write a script to select an anchor and insert an <img> .我需要编写一个脚本到 select 一个锚点并插入一个<img> There are several <a> 's within a div that has an id of _nwa_social_logins .在 id 为_nwa_social_logins的 div 中有几个<a> I need to add an img tag to one of those.我需要在其中一个上添加一个img标签。 I'm not sure of the best way of doing this.我不确定这样做的最佳方法。

It's a captive portal page served up by a product we use, and the bit I'm interested in looks like this:这是一个由我们使用的产品提供的强制门户页面,我感兴趣的部分如下所示:

<div id="_nwa_social_logins">
  <a class="btn btn-facebook" href="<url>/guest/social-media.php?oauth_init=1&amp;oauth=facebook" title="">
    <i class="icon-facebook"></i> Facebook
  </a>
  <a class="btn btn-linkedin" href="https://<url>/guest/social-media.php?oauth_init=1&amp;oauth=linkedin" title="">
    <i class="icon-linkedin"></i> LinkedIn
  </a>
  <a class="btn btn-google" href="https://<url>/guest/social-media.php?oauth_init=1&amp;oauth=google" title="">
    <i class="icon-google"></i> Google
  </a>
  <a class="btn btn-twitter" href="https://<url>/guest/social-media.php?oauth_init=1&amp;oauth=twitter" title="">
    <i class="icon-twitter"></i> Twitter
  </a>
  <a class="btn btn-github" href="https://<url>/guest/social-media.php?oauth_init=1&amp;oauth=azure" title=""><img src="images/icon-microsoft.png" align="middle">Microsoft Azure AD
  </a>
  <a class="btn btn-github" href="https://<url>/guest/social-media.php?oauth_init=1&amp;oauth=amazon" title="">Amazon</a>
</div>

So far I have到目前为止我有

let items = document.querySelector('#_nwa_social_logins a');

To be honest I don't know how to even check if that has selected anything.老实说,我什至不知道如何检查它是否选择了任何东西。

I need to select the Amazon anchor and set an <img> for the button.我需要 select 亚马逊锚并为按钮设置一个<img> If the selection above gives me a list of <a> s (objects?) can I loop through them and look for one that has an href value that ends with 'amazon'?如果上面的选择给了我一个<a> s(对象?)的列表,我可以遍历它们并寻找一个 href 值以“amazon”结尾的值吗?

Thank you谢谢

You can do this:你可以这样做:

<script>
    window.addEventListener('load', () => {

        let links = document.querySelectorAll('#_nwa_social_logins a');
        links.forEach((link, index) => {
            if (link.getAttribute("href").toLowerCase().lastIndexOf('amazon') >= 0)
                link.innerHTML = '<img src="someimage">';
        });

    });
</script>

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

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