0

I often see string concatenation inside jQuery selectors:

var $field = $('.' + field, $form);
var $label = $('label[for="' + $field.attr('id') + '"]');
var $elem = $('#' + elem);

Since periods and colons are valid in element ids (and who knows what might be in other attributes), is code like this not potentially dangerous?

I have found that some selectors aren't trivial to write in any other way - so what is the standard practice? Native DOM methods are not always available.

I have always avoided weird characters in ids and the like, but when writing tools for general use by others it would be nice to avoid that caveat.

Community
  • 1
  • 1
Flash
  • 13,804
  • 11
  • 65
  • 91

2 Answers2

0

When you have full control over the content in the string, then it's not a problem, but for a library tool it would be a problem.

Simply don't accept a name or identity for the tool, accept a complete selector or an element/jQuery reference. That way it's the responsibility of the person using the tool to create a working selector.

Guffa
  • 640,220
  • 96
  • 678
  • 956
  • I like that idea. In my particular tool though, I have a list of names and ids of form fields specified server-side which are used again when the form is posted back (required fields for example). Specifying `['name1','name2','name3']` server-side is simply the easiest option for the user, and then my code handles the rest. – Flash Aug 13 '12 at 11:24
0

Your first and third examples are common, and harmless so long as you control what's in field and elem.

I never use the second form, and would write it like so:

var match = $field.attr('id');      // or $field[0].id
var $label = $('label').filter(function() {
    return this.getAttribute('for') === match;
});

thus completely avoiding the need to worry about escaping the contents of match.

Alnitak
  • 313,276
  • 69
  • 379
  • 466
  • But isn't this way more expensive - since it won't use the browser's native `querySelector` or similar? – Flash Aug 13 '12 at 11:12
  • @Andrew it's _potentially_ (slightly) more expensive, depending on just how many `label` elements there are. I wouldn't worry about the difference unless this call was being made repeatedly in a tight loop. – Alnitak Aug 13 '12 at 11:20
  • Thanks - why would you never use the second if the first and third are OK? – Flash Aug 13 '12 at 11:28
  • @Andrew consistency of style, I guess. It's the need to worry about quoting levels that tips that one over the edge for me. – Alnitak Aug 13 '12 at 12:00