更改元素位置

时间:2018-01-14 17:14:38

标签: javascript jquery html

我有示例页面

<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>

我需要在类.testimonial-content__special的最近div中移动div .testimonial-example,所以我需要将每个.testimonial-example移动到.testimonial-content__special,但是它们应该在他们的.testimonail-中公共div,而不是所有.testimonial-example in first .testimonial-content__special。

我试过这个

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

这个

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

也许我犯了错误,或者只是错误的代码,我不知道,有人可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

如果您尝试对每个元素执行此操作,请使用.each循环。然后,您将使用$(this)访问当前元素。然后你可以将元素附加到你选择的元素上。

$('.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