LoginSignup
7

More than 5 years have passed since last update.

ブラウザ標準API DOMトラバース用 まとめ

Last updated at Posted at 2015-03-18

DOM Elementの検索と走査を標準APIでどこまでできるか調べました。
脱jQueryを目指しています。

検索

querySelectorAll

原則としてdocument.querySelectorAllを使います。

引数にはCSSセレクタを指定できます。カンマで区切って複数つけることもできます。

たとえば

var matches = document.querySelectorAll( "div.lightbox, div.popup" );

文書中の、 "lightbox" または "popup" のクラス名を持つすべての div 要素のノードリストを返します。

特定のelement配下を検索したい場合はelement.querySelectorAllを使います。

たとえば

var matches = document.body.querySelectorAll('p');

querySelector

要素が一個しか取れないことがわかっている場合、document.querySelectorを使っても良いです。
インデックスアクセスを省略できます。

var el = document.body.querySelector("#hoge");

element.querySelectorもあります。

走査

Nodeインターフェース

DOMはツリー構造です。Nodeインターフェースには、ツリー構造の構成要素を走査するためのプロパティがあります。
Document、Element、TextNodeが本インターフェースを持ちます。

親ノード

  1. parentNode 親ノード

子ノード

  1. childNodes 子ノードの collection
  2. firstChild 最初の子ノード。子ノードがなければ null
  3. lastChild 最後の子ノード。子ノードがなければ null

兄弟ノード

  1. nextSibling 次のノード。なければnull
  2. previousSibling 前のノード。なければnull

ただし、これらのAPIではElementとTextNodeを両方を取得します。

ParentNodeインターフェース

子ノードのうち、Elementだけを取得する場合はParentNodeインターフェースのプロパティを使用します。
Element、Document、DocumentFragmentが本インターフェースを持ちます。

  1. children 子Elementの collection
  2. firstElementChild 最初の子Element。子Elementがなければ null
  3. lastElementChild 最後の子Element。子Elementがなければ null

NonDocumentTypeChildNodeインターフェース

兄弟ノードのうち、Elementだけを取得するにはNonDocumentTypeChildNodeインターフェースのプロパティを使います。
Element、CharacterDataが本インターフェースを持ちます。

  1. nextElementSibling 次のElement。なければnull
  2. previousElementSibling 前のElement。なければnull

参考リンク

[DOM連載①] これが使えなきゃ始まらない DOMで要素の参照を使いこなす - WEBサービス構築ブログ

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
7