Bite code
Bite code

Reputation: 596793

Set a context so a direct children of body is never selected with jQuery

I have the following HTML code :

<html>
  <head>
  </head>
  <body>
      <div id="never-selected">
      </div>
  </body>
</html>

With JQuery 1.3.2, I would like to create wrapper around $() that allow you to select any element with any combination but the div #never-selected nor its content.

I am trying to do it this way :

_context = false;    
getContext = function() {
    if (_context === false) {
        _gui_dom = jQuery("fuzzy magic selector");
     }
    return _gui_dom;
};


// return a jQuery object filtered to aim the content of the tartiflet GUI only
select = function(selector) {
  return jQuery(selector, getContext());  
};

But I am failling to find the proper formula to cast the "fuzzy magic selector" ;-)

My best shot is jQuery("head *, body *:not(#never-selected, #never-selected *)") but the draw back is that you cannot select head nor body and it's very annoying. Using html * doest work.

Upvotes: 0

Views: 288

Answers (3)

gnarf
gnarf

Reputation: 106342

Would perhaps creating a function that calls jQuery() with the arguments it passes and then automatically .filter()'s it might work?

function select() {
  var jquery = jQuery.apply(args);
  return jquery.filter(":not(#never-selected, #never-selected *");
}

Not sure that works - it was coded in the air.

Upvotes: 0

KyleFarris
KyleFarris

Reputation: 17548

You can write your own custom selector to parse out the stuff you want using any amount of jQuery necessary to grab those elements. Sometimes the selectors they provide by default can't do everything.

I can't think off the top of my head how to achieve what you are asking but you can do something like this:

jQuery.extend(jQuery.expr[':'],{
    everything_but: function(el,sel) {
        var everything = jQuery(el).clone();
        everything.find(sel).remove();
        return everything;
    }
});

I definitely can't say my implementation will work but it may give you an idea of how you can implement your own selector to achieve what you want.

It can be used as usual. Something like this:

var select = $('*:everything_but(#never-selected)')

Writing you own selector seems to be what you are trying to do with your scripts anyways. Good luck!

Upvotes: 0

Rafael
Rafael

Reputation: 18522

I'm not sure whether I understood the problem, but try using .not() on the result set

select = function(selector){return $(selector).not('#never-selected, #never-selected *')};

Upvotes: 1

Related Questions