ysanmiguel ysanmiguel - 1 month ago 11
jQuery Question

Get element closest to the parent and include it inside - jquery

Hello I have been wrapping elements using jQuery, until now everything is ok but I get stuck trying to find the way to include the < a class="pinterest-anchor" into the < div class="wrapMe".

For now I got this:

<div class="wrapPinImg">
<a href="#" class="pinterest-anchor">
<i class="fi-social-pinterest"></i>
</a>
<div class="wrapMe">
<img src="img.png" class="wrapMe" />
</div>
</div>


I need this (Include class:pinterest-anchor inside .wrapMKe):

<div class="wrapPinImg">
<div class="wrapMe">
<a href="#" class="pinterest-anchor">
<i class="fi-social-pinterest"></i>
</a>
<img src="img.png" class="wrapMe" />
</div>
</div>


The "more or less" code idea:

$(".wrapPinImg img").each(function() {
$(this).parent(".wrapMe").closest("a").find(".pinterest-anchor").appendTo(".wrapMe");
});


/***************************************************************************/

to get a better idea about what I'm trying to do here is the whole thing:

/*HTML*/
<div class="wrapPinImg">
<a href="#" class="pinterest-anchor">
<i class="fi-social-pinterest"></i>
</a>
<img src="img.png" class="wrapMe" />
</div>
/*JQUERY*/
$(".wrapPinImg img").each(function() {
var floatStyle = $(this).attr('style');
$(this).attr('style', '');
$(this).wrap('<div class="wrapMe"></div>');
/* $(this).parent(".wrapMe").closest("a").find(".pinterest-anchor").appendTo(".wrapMe"); -- HERE THE PROBLEM*/
$(this).parent(".wrapMe").attr('style', floatStyle );
});


Thank you very much!!!

Answer

Use a combination of next() to select the next element and prepend() to move the element into the next element (wrapMe)

$('.pinterest-anchor').each(function(){
$(this).next().prepend($(this));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div class="wrapPinImg">
    <a href="#" class="pinterest-anchor">
        <i class="fi-social-pinterest"></i>
    </a>
    <div class="wrapMe">
        <img src="img.png" class="wrapMe" />
    </div>
</div>

or use instead of next() the siblings() function:

$('.pinterest-anchor').each(function(){
$(this).siblings('.wrapMe').prepend($(this));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div class="wrapPinImg">
    <a href="#" class="pinterest-anchor">
        <i class="fi-social-pinterest"></i>
    </a>
    <div class="wrapMe">
        <img src="img.png" class="wrapMe" />
    </div>
</div>

Comments