简体   繁体   中英

Looping through child elements of getElementsByClassName nodelist. Can't get it to work properly

I have a webpage with a series of dynamically rendered images that I want to target and change their src attribute with a script, depending on some other logic. I do not have access to their specific markup, but wrapped each one in a div element with the classname "siteavatar".

I am trying to loop through each.siteavatar element and then target their child image element.

I have placed the following code at the bottom of my footer, right before the closing body tag (so placement in the DOM timeline shouldn't be an issue):

    <script>
   
    window.onload = function() {
        var siteAvatars = document.getElementsByClassName("siteavatar");
      console.log(siteAvatars);
     
      siteAvatars.forEach(function(siteAvatar){
          console.log(siteAvatar.querySelector(".avatar"));
      });
    }
    
</script>

The console will succesfully log the siteAvatars variable, but nothing I do will get it to recognize the loop. I have tried multiple different approaches, such as siteAvatar.children, etc.

I have also tried a more regular for loop, with no success:

<script>

window.onload = function() {
    var siteAvatars = document.getElementsByClassName("siteavatar");
   
   for (var i = 0; i < siteAvatars.length; i++) {
       console.log(siteAvatars[i].children)
   }
  console.log(siteAvatars);
}

The problem seems to be looping through the siteAvatars nodelist itself; if I switch the console.log to siteAvatars[i].style.display = "none" / siteAvatar.style.display = "none", that does not work either.

It seems to me there is something obvious I am missing that is outside the scope of what I am troubleshooting on. Any ideas of what it might be? Thank you so much!

You can accomplish this with a for loop. Use querySelector to get the child element.

 window.onload = function() { var siteAvatars = document.getElementsByClassName("siteavatar"); var numSiteAvatars = siteAvatars.length; for (var i = 0; i < numSiteAvatars; i++) { var sa = siteAvatars[i]; var a = sa.querySelector(".avatar"); console.log(a); } }
 <div class="siteavatar"> <img src="" class="avatar" /> </div> <div class="siteavatar"> <img src="" class="avatar" /> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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