misticx
misticx

Reputation: 65

If div has image put that img in other div

I know its sounds a bit crazy, but im doing some pretty complex (complex for me, not for better JS coder) WordPress theme and text in articles expands on hover,and post images shows in different div, and other stuffs. Anyhow I need a function that will check every post (article) and if post have img in it to put that img in other div, if not, live it as it is. I was never good at if else statements, I tried something but it didn't helped.

var picture = $('.post p').find('img');    
$(this).find('.postimage').empty().append(picture);

This worked as a test, but of course it appends image from first post to all "postimage" divs, and its not a wanted solution.

Upvotes: 0

Views: 378

Answers (2)

GregL
GregL

Reputation: 38121

Use the .each() method to operate on each matched item individually.

e.g.

var picture = $('.post p img').each(function(index, element) {
    // the following line will need to change depending on how you need to find the correct .postimage div from the .post div
    $(this).closest('.post').find('.postimage').empty().append(element); 
});

Upvotes: 2

Karl Knechtel
Karl Knechtel

Reputation: 61526

No conditional logic is necessary.

$('.post p img') is "all the images that are inside p's inside post-class div's". In other words, exactly the set of images you want to move.

If there is more than one 'postimage' div, then you are going to have to be more clear about your logic for determining which image goes in which div.

Upvotes: 0

Related Questions