So far my experience with Javascript has not required too much dealing with its raw form. I’m a big fan of the jQuery library and I’ve heard described as a swiss army knife for Javascript. I think that’s an understatement though, it goes beyond just being a toolset. I believe it is a framework in its own right. And in fact, it pushes all your Javascript code into a more structured form.
I recently fixed a problem with a website that was developed by someone using raw Javascript. Basically it failed to work in IE. The underlying problem was that IE doesn’t recognise the visual text of a drop down select box in the DOM of the page as the ‘value’ of the element in the drop down select box.
So if you selected “5pm” from the box, the Javascript can’t be:
foo = frm.select[bar].value;
It has to be:
foo = frm.select[bar].text;
If you want it to work across all the browsers. In jQuery, you would never even write code like the above. You’d be using the CSS selectors:
$("#date_select").text();
The above would find the element with id ‘date_select’ and extract its text. Why the dollar sign? It tells Javascript we’re dealing with the jQuery library.
So you see, jQuery just looks different to raw Javascript most of the time. For example, take a load of this raw Javascript:
document.getElementById("x20").style.display='none';
document.getElementById("x21").style.display='none';
document.getElementById("x22").style.display='none';
var d = frm.Dates;
var dval = d.options[d.selectedIndex].text;
var idx;
for (x=frm.Times.length;x>0;x=x-1)
{
frm.Times.remove(x);
}
Ugh, messy. jQuery steps away from the ‘document’ rubbish by using the CSS selectors mentioned previously. And the for loop? jQuery provides you with functions to iterate throughout CSS selected elements:
$("#times_list li").each(function () {
this.remove()
}
Where ‘this’ is one of the CSS selector’s matched elements, iterated by the ‘each’ function.
