JS 属性値を取得・追加・削除する方法 分かりやすい解説

JS 属性とプロパティを理解しよう Java Script
スポンサーリンク

今回は、「属性とプロパティ」について見ていきましょう。

ここで言う「属性」とは、HTMLで書かれているものになり、「プロパティ」とは、DOMオブジェクトの中にあるものを言います。

言葉で説明するよりも、例を参考に早速使い方を見ていきましょう。

スポンサーリンク

属性値を取得・追加する

属性値を取得

HTML

    <section id="sector1">
      <h2 id="fruits">果物</h2>
      <p id="banana">ばなな</p>
      <p id="apple">りんご</p>
      <p id="grape">ぶどう</p>
      <p id="orange">オレンジ</p>
      <p class="strawberry">いちご</p>
      <a href="https://aftercovid20.com/">アフターコビット</a>
      <label for="name">あなたの好きな果物</label>
      <input type="text" id="like" required="required" size="10" />
    </section>
let element = document.getElementById("sector1");

console.log(element.children[0].id);

fruits

属性値を取得するには、「element」の後に属性名を記述します。

for (let i = 0; i < element.children.length; i++) {
  console.log(element.children[i].id);
}

fruits
 banana
 apple
 grape
 orange
3 
 like

指定した属性名のみ返されます。

console.log(element.children[0].getAttribute("id"));

fruits

getAttribute()」メソッドを使っても取得することが出来ます。

属性値を追加

HTML
   <p class="strawberry">いちご</p>
console.log(element.children[5].className);

strawberry

クラス名「strawberry」を持つ要素に、id名「sky」を追加してみます。

element.children[5].id = "sky";

console.log(element.children[5].id);

sky

id名が追加されました。

element.children[5].setAttribute("id", "sky");

console.log(element.children[5].getAttribute("id"));

sky

setAttribute(name, value)」メソッドを使っても追加することが出来ます。

attributes

let attNames = element.children[8].attributes;
for (let i = 0; i < attNames.length; i++) {
  console.log("属性名" + attNames.item(i).name);
  console.log("属性値" + attNames.item(i).value);
}

 属性名type
 属性値text
 属性名id
 属性値like
 属性名required
 属性値required
 属性名size
 属性値10

attributes」プロパティを使うと、要素の属性一覧を参照出来ます。

getAttributeNames()

let element2 = document.getElementById("sector1");
let getNames2 = element2.children[8].getAttributeNames();

for (let i = 0; i < getNames2.length; i++) {
  console.log("属性名" + getNames2[i]);
}

 属性名type
 属性名id
 属性名required
 属性名size

getAttributeNames()」を使うと、要素の属性名を配列で返します。

removeAttribute

let element1 = document.getElementById("sector1").children[8];
element1.removeAttribute("id");

let getNames = element1.getAttributeNames();

for (let i = 0; i < getNames.length; i++) {
  console.log("属性名" + getNames[i]);
}

 属性名type
 属性名required
 属性名size

removeAttribute」メソッドを使うと、指定した属性を削除します。

ここでは「id」を削除しています。

スポンサーリンク

あとがき

前回から沢山のプロパティや属性が出てきているので、混乱されている方も多いと思います。

また、似たようなプロパティもあるので、実際にどれを使ったら良いか迷うこともあると思います。

使う人の好みもあったり、チームの場合はルールもあるので、一概にどれが良いかは言えませんが、その都度状況に合わせて使用することになると思います。

今回も最後までお読み頂きありがとうございました。

タイトルとURLをコピーしました