jQuery - 根据父div类删除div

时间:2010-09-08 00:30:25

标签: jquery jquery-selectors

我正在尝试创建一个jQuery脚本,它将基于父div的类来删除div / s,例如基于下面的父div类,即one-column我想删除divs { {1}}& sideColumn-two

sideColumn-three

如果父母的div类是<div id="footer" class="one-column"> <div class="wrapper"> <div class="contentColumn"> Main Content Column </div> </div> <div class="sideColumn-one"> Side Column 1 </div> <div class="sideColumn-two"> Side Column 2 </div> <div class="sideColumn-three"> Side Column 2 </div> </div> ,那么它会删除div two-columnsideColumn-one,依此类推。

附加信息 - 父div被调用如下:

sideColumn-three

div one-column one-column-three one-column-two-one two-columns-left-sidebar two-columns-right-sidebar two-columns-equal two-columns-equal-right two-columns-50 two-columns-stacked-left two-columns-stacked-right two-columns-mixed two-columns-mixed-left two-columns-mixed-content-left three-columns-mid three-columns-equal three-columns-sidebars-right three-columns-sidebars-left four-columns-equal four-columns-mag 永远不会删除

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:3)

编辑:更新标记

var num = $("#footer").attr("class").replace("-column","");
$("#footer > div:gt(0):not(.sideColumn-" + num + ")").hide();​

You can try it here


上一个回答:不改变你的标记,你可以这样:

var nums = { one: 1, two: 2, three: 3 };
var num = $("#test").attr("class")​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​.replace("-column","");
$("#test > div:not(.col" + nums[num] + ")").hide();​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

You can give it a try here,但是如果你通过给父母提供相同的类来简化它,例如:

<div id="test" class="col1">
    <div class="col1">
        Col 1
    </div>
    <div class="col2">
        Col 2
    </div>    
    <div class="col3">
        Col 3
    </div> 
</div>​

脚本变得更简单,如下所示:

$("#test > div:not(." + $("#test").attr("class") + ")").hide();​

You can try that version here,如果您想删除而不是隐藏它们,只需将.hide()替换为.remove()