Yaroslav Saenko
Yaroslav Saenko

Reputation: 587

Change element position

I have example page

<div class = "tistimonials">
    <div class = "testimonail-common">
        <div class = "testimonial-content">
            <div class = "testimonial-content__special"></div>
        </div>
        <div class = "testimonial-content2">
            <div class = "tistimonial-wrapper">
                <div class = "testimonial-example">example1</div>
            </div>
        </div>
    </div>
    <div class = "testimonail-common">
        <div class = "testimonial-content">
            <div class = "testimonial-content__special"></div>
        </div>
        <div class = "testimonial-content2">
            <div class = "tistimonial-wrapper">
                <div class = "testimonial-example">example2</div>
            </div>
        </div>
    </div>
</div>

I need to move div with class .testimonial-example inside the closest div with class .testimonial-content__special, so I need to move each .testimonial-example to .testimonial-content__special, but they should be inside their .testimonail-common div, not all .testimonial-example inside first .testimonial-content__special.

I tried this

$('.testimonial-example').appendTo($(".testimonial-content__special"));

And this

$('.testimonial-example').appendTo(.closest($(".testimonial-content__special")));

Maybe I made mistake or it is just wrong code, I don't know, can someone help me?

Upvotes: 1

Views: 81

Answers (1)

Joel St&#252;dle
Joel St&#252;dle

Reputation: 367

if you try to do this for every element, use a .each loop. you will then have the current element accessible with $(this). then you can append the element to your element of choice.

$('.testimonial-example').each(function() {

    // get the target element. 
    // .closest() only checks anchestors but not the anchestors children.
    var target = $(this).closest('.testimonail-common').find('.testimonial-content__special');
    target.append($(this));

});

hth, joel

Upvotes: 1

Related Questions