Alain
Alain

Reputation: 36954

How to inhib special chars of a string to use it as a jQuery selector?

Consider the following example :

<input type="text" id="#ab>cd.ef" value="foo" />

<script type="text/javascript">
  var id = '#ab>cd.ef';
  alert($('#' + id).length);
</script>

This results in a syntax error, so I am looking for something to inhib the special chars of a selector.

Of course, for this single example, I can do :

alert($('input').length);

But I will use this principle to use dynamic selectors like :

return $('input[name="' + $(elem).attr('name') + '"]:checked').val();

Even if my "name" attribute contains special chars.

So here is my question : How to inhib special chars of a string to use it as a jQuery selector ?

Upvotes: 1

Views: 38

Answers (1)

Yograj Gupta
Yograj Gupta

Reputation: 9869

You can try this, enclosed id in single quote and check in attribute selector

var id = '#ab>cd.ef';
alert($("[id='"+id+"']").length);

Upvotes: 2

Related Questions