2017-01-23 59 views
1

経験豊富なjavascriptユーザーにとってはおそらく簡単に思える質問ですが、自分で解決することはできません。次の要素のクラスに応じて要素を表示/非表示する

次のhtml要素に特定のクラスがある場合は、要素(h1)を表示または非表示にするjavascriptコードを追加したいと考えています。ここに親/子供はいないが、次の要素のみ。 Jqueryは既に読み込まれています。あなたの助けを事前に

<h1>This must be displayed because next element is div class="show"</h1> 
<div class="show"> 
    <p>Show header above</p> 
</div> 

<h1>This should not be displayed because next element is NOT div class="show"</h1> 
<div class="dontshow"> 
    <p>Don't show header above</p> 
</div> 

ありがとう:

は、ここでの例です。 について

答えて

3

.prev()を使用すると、直前の兄弟を取得して表示/非表示にすることができます。

$('div.show').prev('h1').addBack().show(); 
 
$('div.dontshow').prev('h1').addBack().hide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<h1>This must be displayed because next element is div class="show"</h1> 
 
<div class="show"> 
 
    <p>Show header above</p> 
 
</div> 
 

 
<h1>This should not be displayed because next element is NOT div class="show"</h1> 
 
<div class="dontshow"> 
 
    <p>Don't show header above</p> 
 
</div>

Refences

+0

を非常に短いnは甘い:) –

1

下記見つけてください

スニペット

$("h1").each(function(index) { 
 
    if($(this).next().hasClass("show")) 
 
    { 
 
    $(this).show(); 
 
    } 
 
    else 
 
    { 
 
    $(this).hide(); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<h1>This must be displayed because next element is div class="show"</h1> 
 
<div class="show"> 
 
    <p>Show header above</p> 
 
</div> 
 

 
<h1>This should not be displayed because next element is NOT div class="show"</h1> 
 
<div class="Hide"> 
 
    <p>Don't show header above</p> 
 
</div>

2

前の兄弟要素を取得するにはpreviousElementSiblingを使用してください。古いブラウザチェックpolyfill optionについては

document.querySelector('.dontshow').previousElementSibling.style.display = 'none'; 
 

 
document.querySelector('.show').previousElementSibling.style.display = 'block';
.dontshow { 
 
    display: none; 
 
}
<h1>This must be displayed because next element is div class="show"</h1> 
 
<div class="show"> 
 
    <p>Show header above</p> 
 
</div> 
 

 
<h1>This should not be displayed because next element is NOT div class="show"</h1> 
 
<div class="dontshow"> 
 
    <p>Don't show header above</p> 
 
</div>

。ただ、脇など

0

、なぜちょうどdivの内側にH1タグを入れない?:

<div class="show"> 
    <h1>This must be displayed</h1> 
    <p>Show header above</p> 
</div> 

<div class="dontshow"> 
    <h1>Don't show</h1> 
    <p>Don't show header above</p> 
</div> 
+0

構造はCMSによって生成されるため。 ^^ – Vinny

+0

CMSはおそらくテンプレートに基づいてコンテンツを生成しています.JSを使用するのではなく編集することができますか? ありがとう、とにかくチェックする^^ – Booboobeaker

関連する問題