「脱jQuery」 生JSで.next()のように隣接した次の兄弟要素を取得する
jQueryなしのネイティブJavaScriptで隣接した同階層にある次の兄弟要素を取得してみます。
jQuery
$('.selector').next();
$('.selector').next('.active');
生JS
function next(node, selector) {
if (selector && document.querySelector(selector) !== node.nextElementSibling) {
return null;
}
return node.nextElementSibling;
}
こんな関数を用意します。 nextElementSibling
で次の要素を取得できます。
// .selectorの次の要素を取得
next(document.querySelector('.selector'));
// .selectorの次の要素で.active要素だったら取得
next(document.querySelector('.selector'), '.active');
第2引数にセレクタを指定でき、 if文 のように使うこともできます。
CSS本執筆しました!!!
CSS本出します!1/29発売予定
— たかもそ@CSS本1/29発売!! (@takamosoo) 2018年12月31日
自分がCSS学びたての頃にもっとはやく知りたかったテクニックを載せています。CSSの基礎知識について解説していないので、中級者〜向けとなります。CSS入門書を読んではみたものの、思い通りに作れない人にオススメです。
よろしくお願いします。https://t.co/fkz1dM03Pj pic.twitter.com/suYyaPqwIs