var selector

I haven’t posted something random like this in a while. I need to post more short content here since all of my long form writing is going on at other venues (more on that soon, I hope.)

Anyway, when building applications there’s often a need to build CSS selectors dynamically. This is typically some existing pattern paired with a loop counter or something pulled from a data attribute.

When I’m faced with that task I like to create a variable (called selector) and craft the selector on its own line. I then pass selector into jQuery. I do this for clarity and cleanliness. The clarity comes from the obvious way in which the selector is constructed. The variable name and the line solely dedicated to building the string makes it pretty clear what’s going on. The cleanliness factor is obviously a matter of opinion, but to me, passing a big string concatenation into jQuery just looks ugly.

So, what does it look like?

//slightly updated with feedback
//rest of a singleton here...
},
selector:function(id){<br />
//take the passed in id and build a selector with it
  var selector = id+&quot; &gt; tr:last&quot;,
	myHTML=&quot;&lt;p&gt;This is my paragraph...&lt;/p&gt;&quot;;<br />
//add some stuff to it
	$(selector).append(myHTML);<br />
},
deleter : function(){
//later on in  different function...
//grab the a data attribute from the element firing this event
//this would be an anchor or a button
var dataId = $(this).attr("data-id");
//build a selector with it
  selector = "#list li[data-my-id="+data-id+"]";
//and remove the element from the list
  $(selector)
    .remove();
//unbind this click and remove the data attribute since
//the target element to delete is gone
$(this).attr("data-my-id","").unbind("click");
}

(Look at that, a nice, painless post knocked out in a few minutes. I could get used to that kind of pace.)

This entry was posted in JavaScript. Bookmark the permalink.

8 Responses to "var selector"