0

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.

3
  • 3
    What do you expect and what is not working? Commented Oct 20, 2012 at 10:37
  • i want detach() .links div and append before .image only for odd wrapper. Commented Oct 20, 2012 at 10:58
  • The .each() method runs a loop through the matched elements, in this case it is all the <div>s with .odd. I don't see you using index or value, value refers to the singular matched element. Why are you doing $('.odd') again inside the .each() loop? Commented Oct 22, 2012 at 0:52

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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'));
});

3 Comments

yes! i want detach() .links div and append before .image only for odd wrapper.
before() function is also detach elements ?
@Furqan The element is still in the dom tree, so it's not necessary to detach it from the dom tree.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.