0
0

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 1 year has passed since last update.

【JavaScript】closest()(クロウセスト)の使い方

Last updated at Posted at 2022-01-27

#closest()とは

直近の親セレクタを指定できる。
###メリット:子要素が全て同じの場合、親要素(自分も含む)で個別に識別できる

※idは同じ値は設定できない

<h2>見出し1</h2>
<div class="aaa">
	<ul class="common-tab">
		<li class="red" data-id="tab_1"><a>タブAAA</a></li>
		<li data-id="tab_2"><a>タブBBB</a></li>
		<li data-id="tab_3"><a>タブCCC</a></li>
	</ul>
<p class="tab_1">タブAAA</p>
<p class="tab_2">タブBBB</p>
<p class="tab_3">タブCCC</p>
</div>

<h2>見出し2</h2>
<div class="aaa">
	<ul class="common-tab">
		<li class="red" data-id="tab_1"><a>タブDDD</a></li>
		<li data-id="tab_2"><a>タブEEE</a></li>
		<li data-id="tab_3"><a>タブFFF</a></li>
	</ul>
<p class="tab_1">タブDDD</p>
<p class="tab_2">タブEEE</p>
<p class="tab_3">タブFFF</p>
</div>

<style>
.red { background-color:red;}
.blue { background-color:#0000FF;},
</style>
 $('div.aaa ul.common-tab li').each(function(){
 	  if($(this).hasClass("red")){
          const target = $(this).data('id');
          $(this).closest('ul.common-tab').siblings(':not(.'+target+')').addClass('blue');
          $(this).closest('ul.common-tab').siblings('.'+target).addClass('red');
      }
 });


$('ul.common-tab li').click(function(){
	$(this).addClass('red').siblings().removeClass('red');
	const target = $(this).data('id');
    $(this).closest('ul.common-tab').siblings().removeClass('red').removeClass('blue').filter('.' + target).addClass('red'); 
     $(this).closest('ul.common-tab').siblings(':not(.'+target+')').addClass('blue');
});

#alert結果

⇛   test1

⇛   test2

⇛   test3

⇛   test4

⇛   test5 abc
0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?