简体   繁体   中英

Get each Children element that has a class and insert before its parent

What I am trying to achieve and failing for some reason is..

With this code structure:

<div class="catProductAttributeGroup">
  <div class="catProdAttributeTitle">TITLE 1</div>
  Content for class "catProductAttributeGroup" Goes Here </div>
<div class="catProductAttributeGroup">
  <div class="catProdAttributeTitle">TITLE 2</div>
  Content for class "catProductAttributeGroup" Goes Here </div>
<div class="catProductAttributeGroup">
  <div class="catProdAttributeTitle">TITLE 3</div>
  Content for class "catProductAttributeGroup" Goes Here </div>

TO DISPLAY LIKE THIS: I want to make sure theres a title to insertBefore(); that's why I have the first line under the function line.

<div class="catProdAttributeTitle">TITLE 1</div>
<div class="catProductAttributeGroup"> Content for  class "catProductAttributeGroup" Goes Here </div>
<div class="catProdAttributeTitle">TITLE 2</div>
<div class="catProductAttributeGroup"> Content for  class "catProductAttributeGroup" Goes Here </div>
<div class="catProdAttributeTitle">TITLE 3</div>
<div class="catProductAttributeGroup"> Content for  class "catProductAttributeGroup" Goes Here </div>

USING THIS:

$(".catProductAttributeGroup").each(function() {
    if ($(this).find(".catProdAttributeTitle").length > 0) {
        $( ".catProdAttributeTitle").insertBefore($(".catProductAttributeGroup"));
     }
});

BUT RENDERING ALL TITLES ON THE TOP OF THE FIRST PARENT LIKE THIS:

<div class="catProdAttributeTitle">TITLE 1</div>
<div class="catProdAttributeTitle">TITLE 2</div>
<div class="catProdAttributeTitle">TITLE 3</div>
<div class="catProductAttributeGroup"> Content for  class "catProductAttributeGroup" Goes Here </div>
<div class="catProductAttributeGroup"> Content for  class "catProductAttributeGroup" Goes Here </div>
<div class="catProductAttributeGroup"> Content for  class "catProductAttributeGroup" Goes Here </div>

Please somebody help me around this THANKS!

Use $(this) inside the each to refer to the current element.

$('.catProdAttributeTitle').each(function() {
    $(this).insertBefore($(this).parent());
});

If the element is nested, use closest() instead of parent() .

$(this).insertBefore($(this).closest('.catProductAttributeGroup'));

Demo

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