「脱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本執筆しました!!!
CSS本出します!1/29発売予定
— たかもそ@CSS本1/29発売!! (@takamosoo) 2018年12月31日
自分がCSS学びたての頃にもっとはやく知りたかったテクニックを載せています。CSSの基礎知識について解説していないので、中級者〜向けとなります。CSS入門書を読んではみたものの、思い通りに作れない人にオススメです。
よろしくお願いします。https://t.co/fkz1dM03Pj pic.twitter.com/suYyaPqwIs