I have a dom element that contains a fully qualified name as part of the id attribute;
<div id="domain\element\div">My Div</div>
It seems impossible to get jQuery to select the element by ID. Here's my experiment;
var $e1 = $('#domain\\\element\\\div');
var $e2 = $('#domain\\element\\div');
var $e3 = $(document.getElementById('domain\\\element\\\div'));
console.log($e1);
console.log($e2);
console.log($e3);
The output of the console displays the first two as empty while the third works;
[]
[]
<div id="domain\element\div">TODO write content</div>
I am using jQuery 1.5.2. Is this a bug with jQuery itself or are my selector strings wrong?
With jQuery selectors, you can find or select HTML elements based on their id, classes, attributes, types and much more from a DOM. In simple words, you can say that selectors are used to select one or more HTML elements using jQuery and once the element is selected then you can perform various operation on that.
All jQuery selectors start with a dollor sign and parenthesis e.g. $ (). It is known as the factory function. Every jQuery selector start with thiis sign $ (). This sign is known as the factory function. It uses the three basic building blocks while selecting an element in a given document. It represents a tag name available in the DOM.
All selectors in jQuery start with the dollar sign and parentheses: $ (). The jQuery element selector selects elements based on the element name. You can select all <p> elements on a page like this:
A jQuery statement typically follows the syntax pattern: $(selector).methodName(); The selector is a string expression that identifies the set of DOM elements that will be collected into a matched set to be operated upon. jQuery selectors return jQuery objects, not DOM objects which are returned from javascript selectors.
If you can change the ID within your HTML code, find some other separator than a backslash \
for your ID so that you can make a valid ID for your selector (see here). An underscore _
would be good.
If you can't alter the HTML, jQuery can still work with backslashes in IDs and ID selectors. Except, you'll need to use four backslashes to match each literal backslash in your ID selector:
$('#domain\\\\element\\\\div')
You achieve this by
Taking the ID:
domain\element\div
Adding the #
symbol and escaping the backslashes for the selector:
#domain\\element\\div
Escaping each pair of backslashes for use in JavaScript strings by doubling them (also notice the quotes):
'#domain\\\\element\\\\div'
Then passing the string to $()
as above.
jsFiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With