caisah
caisah

Reputation: 2087

How to select all body elements except first div

I have this 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>

I want to add a class to all body elements except my first div (which has the id called switcher), when I click on the Large print button.

I have tried

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

and

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

and

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

but none seem to work (the class applies to all elements).

I don't want to find an alternate way like selecting only p elements. I just want to understand why the selectors I used don't work...

Upvotes: 3

Views: 1502

Answers (2)

xdazz
xdazz

Reputation: 160833

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

Upvotes: 1

jAndy
jAndy

Reputation: 235992

You need to exclude the document.body itself. Like

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

This will query for all children of body, excluding #switcher. Maybe more convinient:

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

Upvotes: 4

Related Questions