2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

javascriptでjqueryのclosest的な事をしたい

Posted at

始まり

離れた関連する親要素が欲しいけど、parentNode.parentNode〜とか書くのはかなりよろしくない。
jQueryのclosest()便利!
でもできればjQueryは使いたくないので自前でそれっぽいのを用意。

html
<div id="idiv">
  <div class="div">
  <ul class="ul" id="idul">
    <li class="li" id="idli"><span id="getParent">child</span></li>
  </ul>
  </div>
</div>
closest的な
var closest = function(query,parent) {
  if (!parent) { #初めて探しに行ってるか
    var elm = event.target;
  } else {
    var elm = parent;
  }
  var gparent = elm.parentNode;
  var selector = query.substr(0,1); #'.'or'#'を取得
  var query_string = query.substr(1); #'.'or'#'を取り除く
  var is_class = (selector === '.'); #classなの?
  var is_id = (selector === '#'); #idなの?
  if (is_id) {
    var has_query = gparent.getAttribute('id') === query_string;
  } else if (is_class) {
    var has_query = gparent.classList.contains(query_string);
  }
  if (has_query){
    return gparent;
  } else {
    #マッチするまで繰り返し
    return closest(query,gparent);
  }
}
getNode.addEventListener('click',function(){
  var id = '#idiv';
  var node = closest(id);
  console.log(node) # #idvをゲット!
})

parentsとかparentsUntilとかfindとかはあまり使わなそうだけど、使いそうになったらそのときは。

2
1
2

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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?