1
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?

More than 5 years have passed since last update.

初心者による DOM 要素ノードの取得一覧-2

Last updated at Posted at 2020-01-11

ノードウォーキング

queryメソッドやgetメソッドを使いたいときには、ピンポイントで特定の要素を指定しないといけないため使いずらい時がある。その時に、近くの要素を指定した後にその近くの要素を取得する方法がある。これがノードウォーキングというものである。つまり、

getメソッドやqueryメソッドで特定の要素を取得した後、近接するノードはノードウォーキングで取得する。

相対関係によりノードを取得するプロパティ

親ノード : parentNode
兄ノード : previousSilbing
兄要素 : previousElementSilbing
弟ノード : nextSilbing
弟要素 : nextElementSilbing
最初の子ノード : firstChild
最初の子要素 : firstElementChild
最後の子ノード : lastChild
最後の子要素 : lastElementChild
すべての子ノード : childNodes

node(ノード)とsilbing(要素)の二つがあるが、ノードにはたくさんの種類がありそのうちに要素ノードが存在する。ノードの種類を表すnodeTypeプロパティがあり、

1 : 要素ノード
2 : 属性ノード
3 : テキストノード
...etc

実装方法

select id="car"要素の配下にあるoptionのvalue値を列挙するコードをいろいろな手法でやってみる。

childNodes

sample.html
<form>
 <select id="car">
  <option value="トヨタ">トヨタ</option>
  <option value="日産">日産</value>
  <option value="ホンダ">ホンダ</value>
 </select>
 <input type="submit" value="送信" />
</form>
sample.js
let s = document.getElementById('car')
//基準ノードの子ノードをすべて取得
let opts = s.childNodes
for(let i = 0, length = opts.length; i < length; i++){
 let opt = opts.item(i)
 //opt.nodeTypeで要素ノードかを判断 -> 要素ノードならその中身を出力
 if(opt.nodeType === 1){
  console.log(opt.value)
 }
}

firstChilds / nextSibling

sample.js
let s = document.getElementById('car')
let child = s.firstChild
//子供が存在する
whils(child){
 if(child.nodeType === 1){
  console.log(child.value)
 }
 //次の兄弟に
 child = child.nextSibling
}

firstElementChild / nextElementSibling

sample.js
let s = document.getElementById('car')
//次の要素
let child = s.firstElementChild
while(child){
 console.log(child.value)
 //兄弟要素
 child = child.nextElementSibling
}

参考資料

山田祥寛様 「javascript 本格入門」

1
0
0

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
1
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?