DRY jQuery Selectors

If you’ve used jQuery for any amount of time no doubt you’ve found your JavaScript code littered with dozens of hardcoded string selectors. In many cases the same selectors are used in multiple places in the code.

In a relatively simple web page this may not be that big of a deal to maintain. But what about a page or project with a complex UI? What do you do when the ids and class names of the UI elements change thus requiring changes to the selectors found throughout your code?

DRY

The DRY principle comes into play here. For example, in the HTML below there are several elements for which I’ll need to create selectors (the two buttons and the notification and message div’s). I want to define these selectors in one place and then use them wherever necessary in my code.

1
2
3
4
5
6
7
8
9
<div id="wrapper">
<div id="buttons">
<button id="show">Show Messagebutton>
<button id="hide">Hide Messagebutton>
div>
div>
<div style="display: none" id="notification">
<span id="message">span>
div>

The approach I’ve taken is to create an object literal that contains a property for each selector that will be needed.

1
2
3
4
5
6
var selectors = {
showButton: "#show",
hideButton: "#hide",
message: "#message",
notification: "#notification"
};

Using these selectors is as simple as

1
2
3
$(selectors.showButton).click(function() {
// do something
});

If I ever need to tweak the selector for the show button I can make the change in one location and move on. I’ve been using this approach for much of the past year and have been pleased so far. I spend far less time using my IDE’s search and replace functionality.

I’ve put together a simple example of using object literals to encapsulate jQuery selectors. Download the code and try it out.