LoginSignup
4
3

More than 5 years have passed since last update.

HTML5で使用するdatalist,option,select,optgroupはCSSが適用できない。代わりにJavaScriptでDOM要素を変更する必要がある

Last updated at Posted at 2019-02-06

vue.jsを使いながら、HTMLについて色々調べていたら、datalistっていうのを初めて知った。
かなり便利なHTMLタグです。簡単にコンボボックスを実装できる。
以下のようなソースだと、inputタグのlist属性にvalue値を設定するだけで、クリック時にリストを表示できる。

しかしながら、難点があって、CSSが適用できないという制約があるため、リスト自体を装飾したり、リストの幅を大きくしたり、カスタマイズしたいなら、JavaScriptなどでDOM要素を変更する必要がある。

sample.html
<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
</head>

<body>
    <input type="search" name="q" autocomplete="on" list="keywords">
    <datalist id="keywords">
        <option>test1</option>
        <option>test2</option>
        <option>test3</option>
    </datalist>
</body>
</html>

そして表示は以下の通りになる。

スクリーンショット 2019-02-06 22.40.23.png

ちなみに以下のCSS要素はinput要素に対して適用されているため、黒くなる。

input[list] {
        background-color: #0f0f0f;
    }

結果

スクリーンショット 2019-02-06 22.50.14.png

Styling HTML forms
カスタムフォームウィジェットの作り方

4
3
0

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
4
3