Tag Archives: Ext

2xjQuery: Select a Selector

Selectors in jQuery

jQuery JavaScript Library

If you’re familiar with jQuery you should already know what are selectors and how they work. However we’re used to get some DOM element with a specific selector, but actually sometimes you cannot select directly what you need. This is especially true when mixing more than one JavaScript libraries. In my case OpenLayers generated a vector layer and jQuery was supposed to change the vectors fill-color property.

OpenLayers

With the simple $(‘path’) I easily got all vectors in the current document, but the problem was that I took them as text. Thus it came to me to use nested jQuery – $($(‘selector’));

To describe what actually happened in my case, let me show you a breve example.

Example

Here’s a short HTML markup:

<div><span>text text</span></div>

With jQuery I can select both the DIV and SPAN with the simple $(‘div’) and $(‘span’), but just for the example lets assume I’ve only the inner text of the DIV tag:

$('div').html();

That was the case in the OpenLayers/jQuery problem. Now I can easily use another jQuery selector:

$($('div').html());

This will return the same as $(‘span’) – a jQuery object.

jQuery vs. pure JavaScript

The question is: should I use always jQuery in some large jQuery project? Imagine you’re developing a large scale web application where the JavaScript part of it is supported by jQuery. In my case that was the reality. In fact in every, even very big, project there are “pages” where you don’t need much of JavaScript. Such pages can be the “about”, “info” or whatever static page there is.

Well the question is, should I again include the hole jQuery if I need only to toggle the visiblity on a DIV element? Let’s assume you’ve very long text, cutted in the beggining with the “more” link somewhere after the intro. That’s very common, isn’t it? So by clicking on the “more” you toggle the visibility of the rest of the text. Well of course it’s absurt if I include the entire library just to make this.

The right answer by me is to use pure JavaScript, something like that:

document.getElementId('id').style.display = 'block'

That will do the same job without to block the “fast” in other way page!