LoginSignup
107
101

More than 5 years have passed since last update.

[phiary] jQuery の代わりに Selectors API の querySelector/querySelectorAll を使うと良いかもよ♪

Last updated at Posted at 2013-10-26

本家ブログ『phiary』からの転載になります
もしよければこちらからご覧ください -> http://phiary.me/jquery-selector-api-query-selector-all/




今回は Selectors API の querySelector/querySelectorAll についてサクッとメモ.

このメソッドを使えば getElementByIdgetElementsByClassName の代わりに使えて
CSS セレクタでマッチした要素を取得することができます.

jQuery を使うまでもないけど DOM 操作したいなぁなんて時に使えます.

Usage

document のメンバメソッドです.


document.querySelector("#hoge");                // id が hoge の要素を取得
document.querySelector("section>h2");           // section 直下の h2 を取得
document.querySelector("input[type='submit]");  // type が submit の要素を取得
document.querySelector(".foo");                 // class が foo の最初の要素を取得
document.querySelectorAll(".foo");              // class が foo の要素を配列として全て取得
document.querySelectorAll(".foo, .bar");        // class が foo もしくは bar の要素を配列として全て取得

Tips

jQuery っぽく使う

if (window.$ === undefined) {
    window.$ = function(q) {
        return document.querySelector(q);
    }
}

// id が hoge の要素を取得
$("#hoge");

Reference

自分のエントリーw

107
101
1

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
107
101