Select div with random class

I’am using iosslider on my single page.
I need to collect all img src from ‘.wp-pic’ and put them to slider background url.
So what I have:

SLIDER FRAME AND DIV WITH WP PICTURES:

Read More
<div class='my-slider large-9 columns'>
  <div class='sliderContainer'>
    <div class='iosSlider'>
      <div class='slider'>

      </div>
    </div>
  </div>
</div><!--/.slider-->

<div class='wp-pic'>
  <?php if(have_posts()) : ?> 
    <?php while(have_posts()) : the_post(); ?> 
       <?php the_content(); ?>
    <?php endwhile; ?>
  <?php endif; ?>
</div>

/* SLIDER SETTINGS
=============================================*/
.sliderContainer{
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100%;
}
.iosSlider{
  position: relative;
  top: 0;
  left: 0;
  overflow: hidden;
  width: 100%;
  height: 100%;
}
.iosSlider .slider{
  width: 100%;
  height: 100%;
}
.iosSlider .slider .item{
  float: left;
  width: 100%;
  height: 100%;
}

// REMOVE PICTURES PUSHED BY WP AND PUT THEM TO THE IOSSLIDER
  $('.wp-pic').find('img').each(function(){
    var photoSrc  = $(this).attr('src'),
        photoImg  = '<img src="' + photoSrc + '">',
        numbClass = Math.round(Math.random() * 15);
    $('.slider').append('<div class="item photo-template' + numbClass + '">' + photoImg + '</div>');
    $('.wp-pic').remove();
  });

  $('.item').find('img').each(function(){
    var x = $(this).attr('src');
    $('.slider').find('div:contains(photo-template)').each(function(){ 
      $(this).css({
        'background-image'   :'url(' + x + ')',
        'background-size'    :'contain',
        'background-position':'center',
        'background-repeat'  :'no-repeat'
      });
    });
    $(this).remove();
  });

How can I select each class ‘photo-template’ and place on their background collected src?

FIDDLE

Related posts

Leave a Reply

2 comments

  1. You dont need to have different classes to do what you want.

    and you can get it with only one loop. Just loop through each img and then change it’s parent’s css.

    $('.item').find('img').each(function(){
        var x = $(this).attr('src');
        $(this).parent().css({
            'background-image'   :'url(' + x + ')',
            'background-size'    :'contain',
            'background-position':'center',
            'background-repeat'  :'no-repeat'
        });
        $(this).remove();
    });
    

    look at this FIDDLE i’ve made based on yours.

  2. Use jQuery.each() on $(".photo-template"), which will return each element with that class.

    Format:

    $.each( $(".photo-template"), function(el, i) {
      // do something with $(el).find("img").attr("src")
    };