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:

// attempt to select everything that has 'style.top' present
$("[~top]")
// selects nothing because there is no context, default will not do 
// then look into the id=container and give document.body as a context 
$("#container[~top]", document.body )
// still select nothing in the body context which is too wide 
// use '#container' as context 
$("[~top]", "#container")
// selects all elements with style.top, in the given context 

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 :

// attempt to select everything that has attr 'data' present 
$("[data]")
// selects nothing because there is no context, default will not do 
// ok look into the id=container and give document.body as a context
$("#container[data]", document.body )
// still select nothing in the body context which is too wide 
// use '#container' as context 
$("[data]", "#container")
// selects all elements with attr 'data', in the given context 

3 thoughts on “jQuery selector context considered a “good thing””

Comments are closed.