Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select an element having a backslash in its id attribute

Tags:

javascript

While going through official doc ,I am unable to understand that for matching the first div ,how they have written four backslash(\) ,In my opinion there should be two backslash.I am unable to find the valid logic for this reason

 <div id="foo\bar"></div>
 <div id="foo:bar"></div>
 document.querySelector('#foo\\\\bar');  // It matches the first div
like image 253
Danny Avatar asked Feb 21 '18 10:02

Danny


People also ask

Can HTML ID contain slash?

Yes, you can use it, and you can have href="#/name" . No escaping needed. In CSS, it needs to be escaped, e.g. using a selector like #\/name .

How do I select all elements by ID?

Use the document. querySelectorAll() method to get all elements whose id starts with a specific string, e.g. document. querySelectorAll('[id^="box"]') . The method returns a NodeList containing all the elements that match the provided selector.

How do I find id attributes?

You can use attr('id') in jQuery or the id property (or getAttribute('id') ) on the native DOM element. Show activity on this post. Show activity on this post. You can also use conventional .

What is querySelector()?

querySelector() The Document method querySelector() returns the first Element within the document that matches the specified selector, or group of selectors. If no matches are found, null is returned.


2 Answers

This is due to the browser escapes the backslash in the id attribute. So it will become

<div id="foo\\bar"></div>

So inorder to select the element we need to provide \\\\ to select the element.

var elements = document.querySelector('#foo\\\\bar');
console.log(elements);
var elements = document.querySelector('#foo\\bar');
console.log(elements);
<div id="foo\bar"></div>
<div id="foo:bar"></div>

Update based on comment You can read more information regarding this in following links:-

https://mathiasbynens.be/notes/css-escapes

https://www.w3.org/TR/CSS21/syndata.html#characters

like image 116
SAMUEL Avatar answered Sep 29 '22 19:09

SAMUEL


You have two double backslashes. As you know, the backslashe is a "escape" character.

So your selector string become:

#foo\\bar <--- to have this string in a variable, you need to use '#foo\\\\bar'

Now, the double backslash that left (in the string) will be used (again as a escape character) by the querySelector.

You can checkout more details about how selectors can be written here.

like image 27
Rafael Paulino Avatar answered Sep 29 '22 17:09

Rafael Paulino