参考にした動画
学んだこと
31:12のあたり
・getElementById() と getElementsByClassName()
・getElementById()の実験
写経したコード
<html>
<body>
<p>商品の金額 : <span class="class-price">1000</span>円</p>
<p>商品の金額 : <span class="class-price">100</span>円</p>
<p>商品の金額 : <span class="class-price">10</span>円</p>
<button id="id-button">合計を計算する</button>
<p id="id-total-price"></p>
<script>
btn = document.getElementById("id-button")
btn.addEventListener("click",button)
function button(){
prices = document.getElementsByClassName("class-price")
totalPrice = 0
for (let index = 0; index < prices.length; index++) {
totalPrice = totalPrice + Number(prices[index].innerText)
}
totalPriceElement = document.getElementById("id-total-price")
totalPriceElement.innerText = "合計金額:" + totalPrice + "円"
}
</script>
</body>
</html>
getElementById()
と getElementsByClassName()
getElementById()
・getElementByIdメソッドは、HTML要素のid属性を使用して要素を特定する。
・引数に指定する値はHTMLのユニークなidである必要がある。
・HTMLドキュメント内で同じidが複数存在する場合、getElementByIdメソッドは最初にマッチした要素を返す。(文末で実験しています)
ユニークなid
・HTMLのユニークなidは「唯一無二」の意味を持つ。
・HTMLドキュメント内での各要素には、ユニークなid属性値を割り当てる必要がある。
・同じHTMLドキュメント内では、異なる要素間でid属性の値が重複してはいけない。
uniqueの意味
・ただ一つだけの、他に存在しない、唯一(無二)の
余談
ということはユニクロって、、、
getElementsByClassName()
・getElementsByClassNameメソッドの引数に指定するクラス名は、ユニークである必要はない。
・複数の要素が同じクラス名を持っている場合、それらの要素を取得することができる。
・HTMLドキュメント内で同じクラス名を持つ要素が複数存在する場合、getElementsByClassNameメソッドはマッチするすべての要素を返す。
・指定したクラス名を持つ複数の要素がある場合は、それらの要素を取得することができる。
まとめ
・用途によってはclassNameは重複しない方がいい時もあるし重複した方がいい時もある。
重複しない方がいい時(工事中)
・そもそもクラス名は特定の要素を識別するために使用されるものである。
・特定のJSやCSSを操作したい時に予期しないエラーの原因になる。
・クラス名が重複している場合、cssの適用や要素の検索が困難になることがある。
重複しない方がいい時はなくて
重複した方がいい時
・今回の動画の内容
・今回は、配列・繰り返し処理の理解を深めるという目的があり、
その例として、idがclass-priceに指定されているpタグの個数分繰り返し処理を行い、金額の値段を合計して合計金額を出力させるということをしたいから。
getElementById()の実験
・HTMLドキュメント内で同じidが複数存在する場合、getElementByIdメソッドは最初にマッチした要素を返す。
<html>
<body>
<p>商品の金額 : <span class="class-price">1000</span>円</p>
<p>商品の金額 : <span class="class-price">100</span>円</p>
<p>商品の金額 : <span class="class-price">10</span>円</p>
<button id="id-button">合計を計算しない</button>
<button id="id-button">合計を計算する</button>
<p id="id-total-price"></p>
<script>
btn = document.getElementById("id-button")
btn.addEventListener("click",button)
function button(){
prices = document.getElementsByClassName("class-price")
totalPrice = 0
for (let index = 0; index < prices.length; index++) {
totalPrice = totalPrice + Number(prices[index].innerText)
}
totalPriceElement = document.getElementById("id-total-price")
totalPriceElement.innerText = "合計金額:" + totalPrice + "円"
}
</script>
</body>
</html>