【javascript】親要素、子要素、兄弟要素を取得する
HTMLは以下の通りです。親要素、子要素、兄弟要素を取得してみましょう。
<div class="parent_box">
<div class="box1">子要素1</div>
<div class="box2">子要素2</div>
<div class="box3">子要素3</div>
</div>
子要素の取得
children
javascript console.log(box.children);
親要素をクリックしてみてください。
firstElementChild 最初の子要素
javascript console.log(box.firstElementChild);
親要素をクリックしてみてください。
lastElementChild 最後の子要素
javascript console.log(box.lastElementChild);
親要素をクリックしてみてください。
兄弟要素の取得
nextElementSibling 次の兄弟要素
console.log(box.children[0].nextElementSibling);
子要素1をクリックしてみてください。
previousElementSibling 前の兄弟要素
console.log(box.children[2].previousElementSibling);
子要素3をクリックしてみてください。
親要素の取得
parentNode
console.log(box.childeren.parentNode);
// 親要素の子要素の親を取得
// あえてこんな書き方はしませんが
子要素をクリックしてみてください。
children:子要素
firstElementChild:最初の子要素
lastElementChild:最後の子要素
nextElementSibling:次の兄弟要素
previousElementSibling:前の兄弟要素
parentNode:親要素