0

how to select all elements except the div "hola" and childrens

     <body>
        <div id="hola">
            <div>example</div>
            <span>example</span>
        </div>
        <div>not selected</div>
        <span>not selected</span>
    </body>

    $(document).ready(function() {
        $(":not(#hola > *)").click(function(){
            console.log("sdf");
        });
    });

http://jsfiddle.net/Mp9f4/

Ronal Vasquez
  • 109
  • 2
  • 14

2 Answers2

2

I pretty sure you don't want to select all other items, since that would include body.

Try this:

$(function() {
    $("body > *:not(#hola)").click(function(){
        console.log("sdf");
    });
});

It selects all immediate children of body, except for ones with id hola

JSFiddle

Paul Draper
  • 78,542
  • 46
  • 206
  • 285
1

It looks like you actually want not to select all items, but to process clicks on any item but the ones in #hola div (the element itself and its children).

Alas, the way you've chosen - assigning separate click handlers for all the elements but #hola and its children - is destined to fail, as click events bubble.

I'd suggest slightly different approach: use just a single event handler placed on document (as you need to listen for clicks on all the elements), and within this handler check for the event's real target. For example:

  $(document).click(function(e) {
     var $target = $(e.target);
     if ($target.is('#hola') || $target.closest('#hola').length) {
       return false;
     }
     console.log('sdf');
   });

JS Fiddle.

Community
  • 1
  • 1
raina77ow
  • 103,633
  • 15
  • 192
  • 229
  • It is okay to put a click event on the whole document, and check and stop the bubble, but it is way messier than just using the right selector. – Paul Draper Oct 29 '13 at 23:52