如何选择除第一个div之外的所有body元素

时间:2012-07-25 09:54:00

标签: javascript jquery

我有这个HTML:

<body>
    <div id="switcher" class="switcher">
        <h3>Style Switcher</h3>
        <button id="switcher-default">
                Default
        </button>
        <button id="switcher-narrow">
            Narrow Column
        </button>
        <button id="switcher-large">
            Large Print
        </button>
    </div>
    <p>asdfasdfasdfas dsadf</p>
    <p>asd'lfkasdf</p>

    <script src="jquery.js"></script>
    <script src="test.js"></script>
</body>

当我点击大字体div时,我想向除第一个id(其中button称为切换器)之外的所有正文元素添加一个类。

我试过了

 $(document).ready(function(){
   $("#switcher-large").bind("click", function(){       
    $("body:not(:first-child)").addClass("large");      
    });
});

$(document).ready(function(){
   $("#switcher-large").bind("click", function(){       
    $("body:not(div)").addClass("large");       
    });
});

$(document).ready(function(){
       $("#switcher-large").bind("click", function(){       
        $("body").not("#switcher").addClass("large");       
        });
    });

但似乎没有工作(该类适用于所有元素)。

我不想找到仅选择p元素的替代方法。我只想了解为什么我使用的选择器不起作用......

2 个答案:

答案 0 :(得分:4)

您需要排除document.body本身。像

$("body *").not("#switcher").addClass("large"); 

这将查询body的所有子项,不包括#switcher。也许更方便:

$(document.body).contents().not('#switcher').addClass('large');

答案 1 :(得分:1)

$("body").children().not("#switcher").addClass("large");
相关问题