David de la O
David de la O

Reputation: 15

Use images as background and apply to div parents with the same class

I'm trying to use img src as background-image of its parent div (with the same class) with jQuery way, but I need to apply the concrete url of its img child to every div without changing or adding extra classes or id, so that each div parent applies a corresponding different background-image.

My HTML is something like this:

<div class="class">
     <img src="url-image-1" />
</div>

<div class="class">
     <img src=“url-image-2” />
</div>

<div class="class">
     <img src="url-image-3" />
</div>

… and jQuery:

$('.class').css('background-image', 'url(' + $('.class img').attr('src') + ')');
$('.class img').remove();

This code is grabbing the first element (url-image-1) every time; it does not know I want to apply each img to its parent container.

Thanks in advance! (And sorry for my bad english).

Upvotes: 1

Views: 1105

Answers (3)

prasanth
prasanth

Reputation: 22500

Try each function .And select the children image with children('img')

$('.class').each(function() {
  $(this).css('background-image', 'url(' + $(this).children('img').attr('src') + ')');
  console.log($(this).children('img').attr('src'))
  $(this).children('img').remove();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="class">
  <img src="url-image-1" />
</div>

<div class="class">
  <img src="url-image-2"/>
</div>

<div class="class">
  <img src="url-image-3" />
</div>

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337560

The issue is because you're selecting all the .class img elements. Calling attr() on that will only ever get you the first item found in the set.

To fix this, you can provide css() with a function that you can use to find the img related to the current .class element. Try this:

$('.class').css('background-image', function() {
  return 'url(' + $(this).find('img').prop('src') + ')');
});

Upvotes: 0

Super User
Super User

Reputation: 9642

You can use

$('.class').each(function(){
    $(this).css('background-image', 'url(' + $(this).find('img').attr('src') + ')');
    $(this).find('img').remove();
})

Upvotes: 2

Related Questions