本記事では、JavaScriptやjQueryで全ての属性を取得する方法について解説しています。
先輩くん
全ての属性を取得する方法は、JavaScriptとjQueryも変わらないよ!
JavaScriptの学習におすすめ参考書
改訂3版JavaScript本格入門 ~モダンスタイルによる基礎から現場での応用まで
先輩くん
10万部突破したJavaScriptの本が大幅増補改訂し7年ぶりに発売されたよ!
後輩ちゃん
最新の基本文法から、開発に欠かせない応用トピックまで学ぶことが出来るよ!
綺麗なコードが書けるようになる!
リーダブルコード-より良いコードを書くためのシンプルで実践的なテクニック
先輩くん
より良いコードを書きたい人におすすめの本だよ!
後輩ちゃん
10以上前の書籍ですが、内容は今でも役に立つものばかりです!
attributesプロパティ
全ての属性を取得するには、attributesプロパティを使用します。基本的な使い方は以下のとおりです。
let sampleElem = document.querySelector("selectors");
let attrs = sampleElem.attributes;
構文解説
- sampleElem:全ての属性を取得したい要素を代入
- attributes:取得した要素に対してattributesプロパティを指定
- attrs:NamedNodeMapが返される
実際に、attributesプロパティを使用して全ての属性を取得するサンプルコードを用意したので、動作確認してみましょう。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
<body>
<img id="img" class="image-sample" src="hoge.png" alt="サンプル画像" />
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="index.js"></script>
</body>
</html>
let imgElem = document.querySelector("#img");
let imgAttrs = imgElem.attributes;
console.log(imgAttrs); // => NamedNodeMap {0: id, 1: class, 2: src, 3: alt, id: id, class: class, src: src, alt: alt, length: 4}
for (let imgAttr of imgAttrs) {
console.log(`属性:${imgAttr.name}`); // => 属性:id 属性:class 属性:src 属性:alt
console.log(`属性値:${imgAttr.value}`); // => 属性値:img 属性値:image-sample 属性値:hoge.png 属性値:サンプル画像
}
attributesプロパティで取得したNamedNodeMapをfor…of文でループさせています。attributesプロパティで返されたNamedNodeMapはnameプロパティで属性を、valueプロパティで属性値を取得することが出来ます。