javascript - 改变元素位置

标签 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-example 的 div 移动到最近的类 .testimonial-content__special 的 div 中,所以我需要将每个 .testimonial-example 移动到 .testimonial-content__special,但它们应该在它们的 .testimonail- 中普通 div,不是所有的 .testimonial-example 都在第一个 .testimonial-content__special 中。

我试过了

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

还有这个

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

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

最佳答案

如果您尝试对每个元素执行此操作,请使用 .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));

});

嗯,乔尔

关于javascript - 改变元素位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48252108/

相关文章:

javascript - 在多维数组中搜索字符串重复项

javascript - extjs tabpanel 需要在 mozilla firefox 浏览器中单击两次选项卡

php - 如何从没有 ID 的 JQuery 函数提交表单

javascript - 使用 i.d 清除 Jquery 中的 div

javascript - 如何用 JEST 测试 promise 递归

javascript - 哈希表比 document.getElementById 更快吗?

javascript - 如何创建本地 MongoDB _id

jquery - 使用 Kendo 拖/放创建多选元素

html - 三列响应式布局,在大屏幕上顶部 div 居中

css - 2列div布局: right column with fixed width,左流体