【问题标题】:jQuery check divs has a class and unwrap if no other classjQuery 检查 div 有一个类,如果没有其他类则解包
【发布时间】:2014-10-28 23:44:39
【问题描述】:

我有两个div's,我想要做的是循环遍历所有 div 以检查 div 是否有一个类 jsn-bootstrap3,我还试图检查 div 是否有任何其他类,如果没有,那么我想删除jsn-bootstrap3 div,以便留下子内容。

<div class="jsn-bootstrap3">
    <div class="wrapper">
        Div one
    </div>
</div>
<div class="jsn-bootstrap3 block">
    <div class="wrapper">
        Div two
    </div>
</div>


$('div').each(function() {
    if ($(this).hasClass()) {
        console.log($(this));
        var class_name = $(this).attr('jsn-bootstrap3');
        console.log(class_name);
    }
});

jsFiddle

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    你可以试试

    $('div.jsn-bootstrap3').removeClass('jsn-bootstrap3').filter(function () {
        return $.trim(this.className.replace('jsn-bootstrap3', '')) == ''
    }).contents().unwrap();
    

    演示:Fiddle

    • 使用类选择器查找类 jsn-bootstrap3 的 div,因为我们不会与其他人做任何事情
    • 使用 filter() 过滤掉任何其他类的 div
    • 使用 unwrap() 和 contents() 删除包装 div

    【讨论】:

    • 差不多了,我也希望从另一个 div 中删除 .jsn-bootstrap3
    • 不需要再次替换该类,因为它已经被删除了。 $('div.jsn-bootstrap3').removeClass('jsn-bootstrap3').filter(function () { return $.trim(this.className) == '' }).contents().unwrap();
    • @vikram 你的代码删除了类 .jsn-bootstrap3 你检查了吗?
    • @RajivRisi 这就是他需要的吗?
    • @RajivRisi 看第一条评论
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-16
    • 2010-10-05
    • 2020-10-06
    • 2019-05-19
    • 1970-01-01
    相关资源
    最近更新 更多