LoginSignup
59
55

More than 5 years have passed since last update.

jQueryセレクタのエスケープ

Last updated at Posted at 2014-03-28

jQueryの小ネタです。

セレクタに使用するときエスケープが必要な文字

公式の説明によれば、この31字

 !"#$%&'()*+,./:;<=>?@[\]^`{|}~

は2つのバックスラッシュ\\\でエスケープする必要があります。

Category: Selectors

To use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[]^`{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \.

エスケープするメソッドを作っておいて

function selectorEscape(val){
    return val.replace(/[ !"#$%&'()*+,.\/:;<=>?@\[\\\]^`{|}~]/g, '\\$&');
}

このようなときに

selectorを動的に組み立てたいようなときに使います。

function(form, val){
...
    var selector = 'input[name="' + name + '"][value="' + selectorEscape(val) +'"]';
    var found = form.find(selector);
...
}
59
55
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
59
55