「脱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本執筆しました!!!