使用JQuery基于父类删除子元素

时间:2014-07-21 19:14:17

标签: javascript jquery

我有一个简单的组织列表,其中唯一的结构差异是某些父div上的类“成员”。我想根据父类的类删除一些子元素。

 <div class="views-row views-row-1 views-row-odd member">
    <div class="views-field views-field-title">
        <span class="field-content"><a href="[Link 1 goes here]">[Name 1 goes here]</a></span>
    </div>

    <div class="views-field views-field-field-phone field-content">
        [Phone 1 goes here]
    </div>

    <div class="views-field views-field-field-email field-content">
        [Email 1 goes here]
    </div>

    <div class="views-field views-field-field-description field-content">
        [Description 1 goes here]
    </div>
</div>

    <div class="views-row views-row-2 views-row-even">
        <div class="views-field views-field-title">
            <span class="field-content"><a href="[Link 2 goes here]">[Name 2 goes here]</a></span>
        </div>

        <div class="views-field views-field-field-phone field-content">
            [Phone 2 goes here]
        </div>

        <div class="views-field views-field-field-email field-content">
            [Email 2 goes here]
        </div>

        <div class=
        "views-field views-field-field-description field-content">
            [Description 2 goes here]
        </div>
    </div>

因为第1组包含类“成员”,所以我希望它保持不变。但是,由于第2组不是会员,我想删除带有.views-field-field-phone和.views-field-field-email类的div。

我相信我需要使用.not创建一个函数。这样:

$(".views-row").not(".member").css("border", "5px solid red");

会正确勾勒出正确的父母,但我很难针对孩子。

有任何见解。

谢谢。

2 个答案:

答案 0 :(得分:1)

jQuery find应该有所帮助:

http://api.jquery.com/find/

具体是:

$(".views-row").not(".member").find(".views-field-field-phone").remove();
$(".views-row").not(".member").find(".views-field-field-email").remove();

答案 1 :(得分:0)

我想这应该做你正在寻找的事情:

$("div.views-row").not(".member").find(".views-field-field-phone, .views-field-field-email").css("color", "red");

编辑:如果要删除,只需在末尾调用remove()方法而不是css

$("div.views-row").not(".member").find(".views-field-field-phone, .views-field-field-email").remove();

看看这个jsBin:

http://jsbin.com/mokuwano/1/edit?html,js,output