简体   繁体   中英

Reposition elements in html with jquery

I can't figure how to achieve this in the best way: Let's say I have:

 <div class="parent"> <div class="child"></div> </div> <div class="parent"> <div class="child"></div> </div> <div class="parent"> <div class="child"></div> </div> 

And I want to move every 'child' right after it's parent.

 <div class="parent"></div> <div class="child"></div> <div class="parent"></div> <div class="child"></div> <div class="parent"></div> <div class="child"></div> 

How can I achieve this?

Update: Also, how can i exclude the parents that have certain attributes? For example, I need to exclude those that have data-anchor=2 and data-anchor=3 I can't figure out how to do this.

$(".parent").each(function(){
    $(this).after($(".child", this));
});

JSFiddle: https://jsfiddle.net/TrueBlueAussie/onsb12jx/

Note: $(".child", this) is just a shorter version of $(this).find(".child")

Excluding elements can use either .not() or :not() or a filter:

eg using .not()

$(".parent").not('[data-anchor=2],[data-anchor=3]').each(function(){
    $(this).after($(".child", this));
});

or using :not pseudo selector

$(".parent:not([data-anchor=2],[data-anchor=3])").each(function(){
    $(this).after($(".child", this));
});

or using a filter() function

$(".parent").filter(function(){
        return $(this).data('anchor') == "2" || $(this).data('anchor') == "3";
    }).each(function(){
    $(this).after($(".child", this));
});

You can achieve this by looping over the .child elements and using insertAfter() to place them after their closest parent .parent element:

$('.parent .child').each(function() {
    $(this).insertAfter($(this).closest('.parent'));
});

Example fiddle

Use

$(".parent").each(function() {
  $(this).after($(this).find(".child"));
});

after() will help you to position the element after the selected element

You can use .after(fn) method with a function as an argument to return the desired behavior, a benefit of it is not to use a loop explicitly, This way it will do this for you internally:

 $('.parent').after(function() { return $('.child', this); }); 
 .parent{border:solid red 3px;} .child{border:solid 3px green; margin:3px 0;} 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="parent"> <div class="child">child</div> parent </div> <div class="parent"> <div class="child">child</div> parent </div> <div class="parent"> <div class="child">child</div> parent </div> 

You can use detach method to do that like so:

$(".parent").each(function() {
  $(this).after($(this).find(".child").detach());
});

Here is the JSFiddle demo

You can check the structure by Inspecting element of the age :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM