Jamie Anderson
Jamie Anderson

Reputation: 1493

Tried to use querySelectorAll but failed

I want to select the first id that has class a.

<li class="a" id="1">1</li>
<li class="a" id="2">2</li>
<li class="a" id="3">3</li>
var c = document.querySelectorAll(".a#1");
c.remove();

I use querySelectorAll but it got an error of

Uncaught SyntaxError: Failed to execute 'querySelectorAll' on 'Document': '.a #1' is not a valid selector.

I know in jquery it is done like $('.a#1').remove() and it will work but I'm using zepto, so I have to figure out in pure js.

Upvotes: 1

Views: 2565

Answers (1)

Aravind Sivam
Aravind Sivam

Reputation: 1099

Id name with the number is not valid but you can query like below

document.querySelector('.a#\\31');

If the first character of an identifier is numeric, you’ll need to escape it based on its Unicode code point. For example, the code point for the character 1 is U+0031, so you would escape it as \000031 or \31 .

For more information refer this Using querySelector with IDs that are numbers

Upvotes: 2

Related Questions