Muhammad Furqan
Muhammad Furqan

Reputation: 324

jquery each() function's proper usage

I am trying to use jquery each() function but i think there is something wrong.
Here is the html and jquery code.

<div class="tribute">
<div class="image"></div>
<div class="links"></div>
</div>

<div class="tribute odd">
<div class="image"></div>
<div class="links"></div>
</div>

<div class="tribute">
<div class="image"></div>
<div class="links"></div>
</div>

<div class="tribute odd">
<div class="image"></div>
<div class="links"></div>
</div>

<div class="tribute">
<div class="image"></div>
<div class="links"></div>
</div>

<div class="tribute odd">
<div class="image"></div>
<div class="links"></div>
</div>

and jquery function

   jQuery('.odd').each(function(index, value){

     var oddLinks = jQuery('.odd').find('.links').detach();
     jQuery('.odd .image').before(oddLinks);

    });

this code is not properly working for me.

Upvotes: 0

Views: 116

Answers (2)

xdazz
xdazz

Reputation: 160943

Did you mean change the position of image and link in .odd div? If so, you even don't need to detach it.

See the live demo.

$('.odd').each(function() {
  $(this).find('.image').before($(this).find('.links'));
});

Upvotes: 1

Esailija
Esailija

Reputation: 140236

Try using the context of the current .odd when iterating:

jQuery('.odd').each(function(index, value) {
    var oddLinks = jQuery(this).find('.links').detach();
    jQuery('.image', this).before(oddLinks);
});

.odd selects all .odd elements on the page.

Upvotes: 3

Related Questions