javascript エラー「Uncaught DOMException: Failed to execute ‘querySelectorAll’ on ‘Document’: ‘a[href^=#]’ is not a valid selector.」の解決方法

javascript エラー「Uncaught DOMException: Failed to execute ‘querySelectorAll’ on ‘Document’: ‘a[href^=#]’ is not a valid selector.」の解決方法

javascriptで、エラー「Uncaught DOMException: Failed to execute ‘querySelectorAll’ on ‘Document’: ‘a[href^=#]’ is not a valid selector.」が発生した場合の原因と解決方法を記述してます。

環境

  • OS windows11 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 107.0.5304.107

エラー内容

アンカーが設定されているnodeの数を取得する以下のコードを実行時に発生。

<a href="#hoge"></a>
<a href="#foo"></a>

<script>

const nodelist = document.querySelectorAll('a[href^=#]');
const len = nodelist.length;

console.log(len);

</script>

エラーメッセージ

Uncaught DOMException: Failed to execute 'querySelectorAll' on 'Document': 'a[href^=#]' is not a valid selector.

画像

firefox(バージョン106)では、下記のエラーとなります。

Uncaught DOMException: Document.querySelectorAll: 'a[href^=#]' is not a valid selector

画像

原因

「querySelectorAll」に指定している「//#」は「バックスラッシュ」か「ダブルクオーテーション」でエスケープが必要なため

解決方法

「バックスラッシュ」か「ダブルクオーテーション」を付ける。

<a href="#hoge"></a>
<a href="#foo"></a>

<script>

const nodelist = document.querySelectorAll('a[href^=\\#]');
const len = nodelist.length;

console.log(len);

or

const nodelist = document.querySelectorAll('a[href^="#"]');
const len = nodelist.length;

console.log(len);

</script>

実行結果