0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

HTMLとJavaScriptのdata属性

Last updated at Posted at 2025-07-18

概要

data属性はHTMLの要素に情報を埋め込むためのカスタム属性。

HTMLではdata-属性名と記述して設定する。

JavaScriptではdataset.属性名と記述して呼び出すことができる。

コード

HTML

<div class="book" data-title="きよしこ" data-author="重松 清">
クリック
</div>

JavaScript

document.querySelector('.book').addEventListener('click', function () {
  const title = this.dataset.title;
  const author = this.dataset.author;

  console.log('タイトル:', title);
  console.log('著者:', author);
});

実行結果

タイトル: きよしこ
著者: 重松 清
  • HTMLでdata-title と書いた場合、Javascriptではdataset.title でアクセスする。

ケバブケースからキャメルケースへの変換

HTMLで data属性をケバブケース(ハイフン区切り)で書いた場合、JavaScriptではキャメルケースとしてアクセスされる。

コード

HTML

<div class="book" data-book-title="舞姫" data-book-author="森 鴎外">
クリック
</div>

JavaScript

document.querySelector('.book').addEventListener('click', function () {
  const title = this.dataset.bookTitle;
  const author = this.dataset.bookAuthor;

  console.log('タイトル:', title);
  console.log('著者:', author);
});

実行結果

タイトル: 舞姫
著者: 森 鴎外
  • data-book_titleのようにdata属性としてスネークケースは使用できない( JavaScriptでアクセスできないため)。
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?