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.)

8 thoughts on “var selector

  1. Can Ajaxian please die now, and not fill me with hope every time a link pops up… kthxbai

  2. Hi Rob,

    I like that everything’s not on one line, but I’m not sure if I agree with the reuse of the ‘selector’ variable. It’s a little confusing.

    I tend to construct the selector inside the $() and use the variable name to describe the captured objects.

    So for example:

    selector: function(id){
    var lastRow = $(id ).children("tr:last"),
    myHTML = "This is my paragraph...",
    navButtons;

    lastRow.append(myHTML);

    navButtons = $("#list li[data-my-id=" + rel + "]");
    navButtons.remove();
    }

    (whether you initialize the variable up top, like lastRow, or in line with the rest of the logic, like navButtons, is really a matter of preference)

  3. Yeah, if I’m going to use a selector more than once I’ll cache it into a variable with the addition of appending $ to the variable name to indicate that it’s a loaded jQuery instance you can chain, etc.

    So it would be var $lastRow = $(id), etc.

    As for the reuse of the variable selector it wouldn’t ever be used more than once per formulation (I would never call $(selector) more than once with the same concatenated string value of selector, I always cache it into a variable) and even then it’s going to be rarely used more than once per method. The example is just an example, especially with the close proximity of usage.

  4. You’re probably looking for a String.Format function.
    Warning thought, most implementations are based on RegExp, which might not be the fastest.
    Usage:

    doStuff:function(id, rel){
    var selector = String.Format(“{0} > tr:last”, id),
    myHTML=”This is my paragraph…”;
    $(selector).append(myHTML);
    selector = String.Format(“#list li[data-my-id={0}]”, rel);
    $(selector).remove();
    }

    and then shorten the thing with shortcut:
    var F = String.Format;

    doStuff:function(id, rel){
    var myHTML=”This is my paragraph…”;
    $(F(“{0} > tr:last”, id)).append(myHTML);
    $(F(String.Format(“#list li[data-my-id={0}]”, rel))).remove();
    }

  5. “As for the reuse of the variable selector it wouldn’t ever be used more than once per formulation (I would never call $(selector) more than once with the same concatenated string value of selector

    The example is just an example, especially with the close proximity of usage.”

    Maybe it’s just me then, but I hate examples that go directly against what the person says they would never do. That’s like saying I would never put my arm in a wood chipper but then sticking it in one just to show what it would look like.

  6. While that’s funny, I do have to point out that that’s not the same value of selector in each example. It changes value with each usage so I’m not doing what I would never do…

    This is what the example shows:

    selector:function(id){
    var selector = id+" > tr:last", //selector = "#id > tr:last" myHTML="<p>This is my paragraph...</p>";
    $(selector).append(myHTML);
    //selector = "#id > tr:last" selector = "#list li[data-my-id="+rel+"]"; //different value. selector = "&#list li[data-my-id=9901902901]" $(selector) .remove(); }

    this is what I would never do

    selector:function(id){
    var selector = id+" > tr:last", //selector = "#id > tr:last" myHTML="<p>This is my paragraph...</p>";
    $(selector).append(myHTML);
    //selector = "#id > tr:last" $(selector) //selector = "#id > tr:last" .show(); }

    Other than the fact I would chain it, I would just cache the selection as I mentioned previously…

    selector:function(id){
    var selector = id+" > tr:last", //selector = "#id > tr:last" myHTML="<p>This is my paragraph...</p>";
    $lastRow = $(selector).append(myHTML);
    $lastRow .show(); }

Comments are closed.