Search code examples
javascriptjqueryhtmlajaxreload

Can I reload multiple divs with jQuery?


I'm currently trying to reload some divs by a class:

jQuery(".avatar-wrapper").load(location.href + " .avatar-wrapper>*", "");
img {
  width: 80px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="avatar-wrapper">
  <img class="avatar" src="https://target.scene7.com/is/image/Target/GUEST_7f86ff7a-22f0-4556-997c-b6dc907a1940?wid=488&hei=488&fmt=pjpeg">
</div>

<div class="avatar-wrapper">
  <img class="avatar" src="https://target.scene7.com/is/image/Target/GUEST_7f86ff7a-22f0-4556-997c-b6dc907a1940?wid=488&hei=488&fmt=pjpeg">
</div>

I've multiple elements with the same class on a page so I expected that all elements getting reloaded with this but sadly it don't works. Maybe I need a direct reference but the best option would be one line of code. Any ideas how I can deal with this?


Solution

  • jQuery's .load() loads remote content into page elements. <img> elements are content-less so this is not going to work. You'd be better off removing all your images then replacing them with the ones from a $.post() response, eg

    $.post(location.href).done(doc => {
      $('.avatar').remove()
      $(doc).find('.avatar').appendTo('#some-container-element')
    })
    

    Alternately, reload an element that wraps your images

    $('#some-container-element').load(`${location.href} #some-container-element`, '')