「脱jQuery」 生JSで.prev()のように隣接した前の兄弟要素を取得する

jQueryなしのネイティブJavaScriptで隣接した同階層にある前の兄弟要素を取得してみます。

jQuery


$('.selector').prev();
$('.selector').prev('.active');

生JS


function prev(node, selector) {
  if (selector && document.querySelector(selector) !== node.previousElementSibling) {
    return null;
  }

  return node.previousElementSibling;
}

こんな関数を用意します。 previousElementSibling で前の要素を取得できます。


// .selectorの前の要素を取得
prev(document.querySelector('.selector'));

// .selectorの前の要素で.active要素だったら取得
prev(document.querySelector('.selector'), '.active');

第2引数にセレクタを指定でき、 if文 のように使うこともできます。

CSS本執筆しました!!!