【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);
![子要素取得](../../images/PC/Programing/parent_children/children.jpg)
親要素をクリックしてみてください。
firstElementChild 最初の子要素
javascript console.log(box.firstElementChild);
![最初の子要素取得](../../images/PC/Programing/parent_children/firstElementChild.jpg)
親要素をクリックしてみてください。
lastElementChild 最後の子要素
javascript console.log(box.lastElementChild);
![最後の子要素取得](../../images/PC/Programing/parent_children/lastElementChild.jpg)
親要素をクリックしてみてください。
兄弟要素の取得
nextElementSibling 次の兄弟要素
console.log(box.children[0].nextElementSibling);
![次の子要素取得](../../images/PC/Programing/parent_children/nextElementSibling.jpg)
子要素1をクリックしてみてください。
previousElementSibling 前の兄弟要素
console.log(box.children[2].previousElementSibling);
![前の子要素取得](../../images/PC/Programing/parent_children/nextElementSibling.jpg)
子要素3をクリックしてみてください。
親要素の取得
parentNode
console.log(box.childeren.parentNode);
// 親要素の子要素の親を取得
// あえてこんな書き方はしませんが
![親要素取得](../../images/PC/Programing/parent_children/parentNode.jpg)
子要素をクリックしてみてください。
![point](../../images/point.png)
children:子要素
firstElementChild:最初の子要素
lastElementChild:最後の子要素
nextElementSibling:次の兄弟要素
previousElementSibling:前の兄弟要素
parentNode:親要素