特定のクラス名を持つ要素を選択するには、getElementsByClassName()メソッドを使用します。
let elements = document.getElementsByClassName('className');Code language: JavaScript (javascript)getElementsByClassName()メソッドは、メソッドに渡したCSSクラス名を持つ要素のコレクションを返します。返されるコレクションはNodeListです。
HTML
<html>
<head>
<title>JavaScript getElementsByClassName() example</title>
</head>
<body>
<div id="container">
<p class="note">The first note.</p>
<p class="note">The second note.</p>
</div>
<p class="note">The third note.</p>
<script src="js/app.js"></script>
</body>
</html>Code language: HTML, XML (xml)app.js
let elements = document.getElementsByClassName('note');
for (let i = 0; i < elements.length; i++) {
console.log(elements[i].innerHTML);
}Code language: JavaScript (javascript)出力
The first note.
The second note.
The third note.getElementsByClassName()はElementのメソッドであるため、コンテナ内の特定のクラスを持つ要素を選択できます。
次の例では、コンテナ内のCSSクラスnoteを持つ要素のinnerHTMLのみを表示します。
let container = document.getElementById('container');
let elements = container.getElementsByClassName('note');
for (let i = 0; i < elements.length; i++) {
console.log(elements[i].innerHTML);
}Code language: JavaScript (javascript)出力
The first note.
The second note.このチュートリアルは役に立ちましたか?