Search in 'id' which contains '/' + jquery

I have DOM elements whose id may contain '/'. I want to use the following formate, since I need all elements with an identifier for Ex:

jQuery('[id=activities/_terp_count]') //returns null 

note that

 jQuery('#activities/_terp_count') //returns null 
+4
source share
3 answers

jQuery('[id=activities/_terp_count]') should really find it (an example is http://jsfiddle.net/jXsvA/ ), although it will be slower than a direct search by ID. It will be faster if you can restrict the selector in some way, for example jQuery('div[id*=activities/_terp_count]') , if you know that tags are always <div> , for example.

+4
source

The above solution works for me, but it is worth noting that there are advantages to the native method of getting the element by id: that is, document.getElementById ('strin / g') will work here in cases where jQuery ("strin / g") will fail (because jQuery uses a parser parser that parses the "/" without special handling. escaping). To get a wrapped jQuery version of this element:

 jQuery(document.getElementById('activities/_terp_count')); 

In fact, if you can’t always precisely control what happens with the actual identifier (say, if you are trying to find a page for an element with the identifier of what was specified in the #hash URL), then a) be careful because it it can be dangerous and b) note that jQuery (document.getElementById (window.location.has.replace ("#", ''))); will work much more reliable than jQuery ("#" + window.location.has.replace ("#", '')); because it will not break so easily.

Example:

 jQuery(document.getElementById("_=_")) //<--- null, or the actual element, if you have one which said crazy, non-compliant id jQuery("#_=_") //<--Uncaught Error: Syntax error, unrecognized expression: #_=_ 

If you do not want your users to be able to violate your code simply by entering a specific URL parameter or hash, avoid using this case if you can, and if you cannot, use your own identifier element.

+7
source

You can use a regular identifier selector if you exit the / - jQuery character is required for special characters (although / does not have spatial meaning in jQuery or CSS, as far as I know)

 $('#activities\\/_terp_count') 
+4
source

All Articles