jQuery selector context considered a “good thing”

Generally speaking and simply put, it is not logical (natural) to query any structure, if the result will contain the whole structure being queried. In (for example) SQL you can not write “select everything from everywhere” or even “select ‘only this thing’ from everywhere”. In JQ we are actually almost always saying : “select this and that, from everywhere”. “everywhere” being document context. Which is not logical and not faster than having a narrower context.

I suggest for the jQuery selection context to be imposed on jQuery users. For speed of selection ? Yes this is one side of my idea. Speed.The other side is “Behaviour” or “the logic of the solution”. The logic of jQuery operating on the DOM tree.

For example and to help us understand this new behaviour. Let us imagine we make an jQuery custom selector which will work but it will be logical to use only in specific contexts ? We implement this as “~” prefix. That “~” prefix means : “a prefix before the name of the css property”. Also imagine jQuery is changed so that context MUST be given IF “~” is used. This custom css property selection will work like this:

This approach would make the whole idea of selecting the “~top” CSS properties more logical. And faster if that matters to anyone? I propose to make the whole jQuery selection, NOT to result in anything IF context which must be bellow document.body, is NOT given. Simply: No context no result.

This will give much more logical behaviour. And I suppose faster jQuery .

For attributes this is even more useful. Because attributes are much less present on the DOM tree nodes than style.properties which are almost everywhere. Browser runtime must discard a lot of nodes before finding the ones which have attributes with a required name. Narrowing a selection context in this scenario should be even more useful. And the imagined usage is this :

3 Replies to “jQuery selector context considered a “good thing””

  1. So if I’m getting it right, you’d like to enforce some stricter coding
    standards to encourage others to always use the context argument to make the
    queries faster?

    That does make sense and with many elements and css querying it may
    significantly speed things up, but that should be a separate plugin as it’s
    independent from the purpose of attribute selectors. An interesting idea –
    if that’s what you were talking about :)

    2009/3/18 Balázs Endrész

  2. jQ documentation
    indeed says that context is either: element or jQuery.
    Here, I think it is silly to give jQuery instance as a context.
    Because it obviously does not achieve any speed advances,

    So the last might be the best :
    Enforce context usage and enforce the context to be dom element.
    This idea can be now enforced like this :

    Of course (c) goes for initial excellent snippet to : Balázs Endrész

Comments are closed.