Friday, October 23, 2015

jQuery Attribute Starts With Selector

Week 2
The internet is littered with forums that debate whether 'tis Nobler in the mind to suffer the Slings and Arrows of standard JavaScript or to use a library like jQuery to make your life a little bit easier. And, while it is all good fun (see parody framework websites like Vanilla JS) I have found, in my experience, that the choice is seldom yours to make. In most of my web development experience, the projects have been sufficiently mature that many of the framework decisions had been decided years ago. Either the web team decided to embrace frameworks, like jQuery, or rely solely on JavaScript. As I mentioned in my earlier post, I have had the opportunity of using jQuery on some projects and confined to standard JavaScript on others. This distinction drastically changed the way I went about solving problems.

There are those, like Stack Exchange user Zirak, who will argue that in order to truly appreciate the time saving benefits of jQuery, one must first understand the underlying JavaScript theory – and I’ll admit a part of me agrees with him. The reason I partially sympathize with Zirak probably stems from the fact that my first web programming internship at Company A did not allow me to use jQuery. Like everyone, when I started programming in JavaScript I found myself getting stuck and resorting to searching the internet for help. As I searched through countless websites, I remember wistfully thinking to myself “I wish I could use jQuery, it looks so much easier!” Often times websites like stackoverflow would have answers to JavaScript questions that said something along the lines of “This is easy to solve…if you can use jQuery” but this did not help me very much and I resorted to scouring JavaScript books at my desk. Let’s take a look at a simple example similar to a real world problem I faced.

Let’s say I wanted to manipulate DOM elements, but not just any elements – only ones with IDs that start with “my-ID”. Using jQuery this can easily be doing using the Attribute Starts With Selector

See my full JSFiddle example.

However, if you wanted to accomplish the same thing using pure JavsScript you would have to select all of the 'span' elements and iterate through to find the ones you are looking for, much less convenient.


See my full JSFiddle example.

As you can see, in this case it was much easier to use jQuery than pure JavaScript. But that does not answer the question, is it better to first understand pure JavaScript and then learn jQuery? I think yes, not only does learning JavaScript first teach you to truly appreciate the simplicity of jQuery, but it also allows you to understand exactly what jQuery is doing to make your life easier. Maybe it is just because I learned JavaScript and then jQuery, but I can say personally that knowing the underlying JavaScript helps me to write better, clearly, and more powerful jQuery code.

No comments:

Post a Comment