2
0

More than 3 years have passed since last update.

【JavaScript】querySelectorなどでCSSセレクターを使うときに](ブラケット)を閉じないとSafariで動いてくれない

Last updated at Posted at 2020-02-12

次のように、querySelectorで要素を取得する際にうっかり]を書き忘れた場合でも、Chromeでは普通に動いてくれます。

foo.html
<input type="text" value="hogehoge" />

<script>
    const element = document.querySelector("input[type='text'")
    console.log(element.value)
</script>

Chromeの場合

スクリーンショット 2020-02-12 9.27.43.png

しかし、Safariで同じことをやろうとすると、次のようなエラーを吐いてしまいます。
The string did not match the expected pattern.

スクリーンショット 2020-02-12 9.25.29.png

スクリーンショット 2020-02-12 9.26.28.png

これはブラケットをしっかり閉じてあげるだけで解決します。

foo.html
<input type="text" value="hogehoge" />

<script>
    const element = document.querySelector("input[type='text']")
    console.log(element.value)
</script>

スクリーンショット 2020-02-12 9.29.59.png

どうやらSafari限定でエラーを吐くようです。

Consider this markup:


And this is where the browser responses to different incomplete selector patterns differ:

document.querySelector('select[name');
Chromium: found 1
Edge: found 1
Firefox: found 1
Internet Explorer: found 1
Safari: DOM Exception 12

引用元 On handling invalid selector strings

普通のブラウザだと正常に動作するのも相まって気が付きにくですね

2
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0