Search code examples
jqueryajaxsiblings

How to addClass into sibling with same class when ajax success


I'm want to creating template with ajax. When button klik it should call the template from sample.html, template structure is more like in var sample, pardon me if its always show error result.

I want to adding class to .contentLoad after ajax success call, so when its success the .contentLoad already in DOM addClass('hidden') except the new .contentLoad I add from ajax.

Is it possible to addClass into sibling with same class when ajax success?

$(document).ready(function() {
  $('.klik').on('click', function() {
    $('.contentLoad').addClass('hidden');
    chooseClick();
  });
});


var sample = '<div class="contentLoad" style="display: none;">' +
  '<div class="contImg">' +
  '<img class="imgres" src="https://static.pexels.com/photos/92957/pexels-photo-92957.jpeg" alt="">' +
  '</div>' +
  '</div>';

function chooseClick() {
  $.ajax({
    url: 'sample.html',
    success: function(temp) {
      $('.load').append(temp).waitForImages(function() {
        $('.loader').hide();
        $('.contentLoad').show();
      });
    },
    error: function() {
      $('.load').prepend('<p>cannot found data</p>');
      $('.loader').hide();
    },
    beforeSend: function() {
      $('.loader').show();
    }
  })
}
.load {
  position: relative;
  width: 1320px;
  margin: auto;
}

.imgres {
  max-width: 100%;
  height: auto;
}

.contentLoad {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 10;
}

.hidden {
  opacity: 0;
  z-index: 1;
}

.loader {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="klik">show</button>
<p class="loader">Loading</p>
<h3>load image here</h3>
<div class="load">
  <div class="contentLoad">
    <div class="contImg">
      <img class="imgres" src="https://now.uiowa.edu/sites/now.uiowa.edu/files/styles/640_wide/public/11_ui_school_of_music.jpg?itok=mxvtE2Am" alt="">
    </div>
  </div>

</div>


Solution

  • you can use this

    var sample = '<div id="newSample" class="contentLoad" style="display: none;">' +
      '<div class="contImg">' +
      '<img class="imgres" src="https://static.pexels.com/photos/92957/pexels-photo-92957.jpeg" alt="">' +
      '</div>' +
      '</div>';
    
    $('.contentLoad:not(#nemSample)').addClass("YourClass")