简体   繁体   中英

JQuery - How to insert element after parent element?

I try to find if an element is on the page. If the element is on the page then find its parent element and insert it after that parent element.

JQuery:

if($('.underline .catIcon').length > 0){
    $('.underline .catIcon').each(function(){
       $(this).insertAfter($(this).parent().find('h2')); 
       $(this).css('float','left');
    });
}

HTML:

<h2 class="underline">
  <div class="catIcon" style="padding-right: 10px;"><!-- element to move -->
    <img class="catIcon" alt="Projects" src="http://www.example.com/storage/images/category/on-site-support56x56.jpg" style="float: left;">
  </div>
  Projekty
</h2>
<!-- here before text and after h2 tag with class underline -->.text
<a class="link2 ui-link" target="_blank" href="http://www.example.com/cz/cs/22.html">>> info</a>

The h2 is the parent's parent element, so you need to use .closest('h2') , not .parent().find('h2') - it looks for a h2 element inside the image's parent( div )

jQuery(function(){
    $('.underline .catIcon').each(function () {
        $(this).insertAfter($(this).closest('h2'));
        $(this).css('float', 'left');
    });
});

Demo: Fiddle

use closest()

you need to go parent .underline then don't find in this

 if($('.underline .catIcon').length > 0){
        $('.underline .catIcon').each(function(){
           $(this).insertAfter($(this).closest(".underline")); 
           $(this).css('float','left');
        });
    }

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