Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move an element after another element using JS or jquery?

I would like to move one DIV element beside another, it is normally like this:

<div class="box-content-top">
 <div class="box-related-product-top">
  <div>  

    <div class="price">
      ...   
    </div>              
    <div class="image">
     ...
    </div>
    <div class="name">
     ...
    </div>
    <div class="cart">
     ...
    </div>


   <div>  

    <div class="price">
      ...   
    </div>            
    <div class="image">
     ...
    </div>
    <div class="name">
     ...
    </div>
    <div class="cart">
     ...
    </div>

  </div>
</div>

I want to change the position of the div with the class .price to be after the .name class, to look like this:

<div class="box-content-top">
 <div class="box-related-product-top">
  <div>  

    <div class="image">
     ...
    </div>
    <div class="name">
     ...
    </div>
     <div class="price"> // HERE
      ...   
    </div> 
    <div class="cart">
     ...
    </div>


   <div>  

    <div class="image">
     ...
    </div>
    <div class="name">
     ...
    </div>
    <div class="price"> // HERE
      ...   
    </div> 
    <div class="cart">
     ...
    </div>

  </div>
</div>
like image 726
user1989195 Avatar asked Jan 27 '13 15:01

user1989195


People also ask

How do you move an element from one element to another?

All you have to do is select the element(s) you want to move, then call an “adding” method such as append() , appendTo() or prepend() to add the selected elements to another parent element. jQuery automatically realises that the element(s) to add already exist in the page, and it moves the element(s) to the new parent.

How do you add an element after another element?

First, select the ul element by its id ( menu ) using the getElementById() method. Second, create a new list item using the createElement() method. Third, use the insertAfter () method to insert a list item element after the last list item element.

How do I move a div to another div?

Answer: Use the jQuery . appendTo() Method You can use the jQuery . appendTo() method to move an element into another element.


2 Answers

You can use insertAfter to move the element. Docs

$('.price').each(function() {
    $(this).insertAfter($(this).parent().find('.name'));
});

Here you have the updated fiddle.

like image 151
techfoobar Avatar answered Oct 02 '22 14:10

techfoobar


$('.box-related-product-top > div').each(function(){
    $(this).find('.image').appendTo(this);
    $(this).find('.name').appendTo($(this));
    $(this).find('.price').appendTo($(this));
    $(this).find('.cart').appendTo($(this));
});

Try it: http://jsfiddle.net/m6djm/1/

like image 32
Nabil Kadimi Avatar answered Oct 02 '22 15:10

Nabil Kadimi