Reputation: 233
Here's a question that will probably seem easy to experienced javascript users but that I can't solve by myself.
I'd like to add a javascript code that displays or hide an element (h1) if the next html element has a specific class. No parent/child here, only next element. Please note Jquery is already loaded.
Here's the example:
<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>
Thanks in advance for your help. regards
Upvotes: 1
Views: 1676
Reputation: 86
Just as an aside, why not just put the h1 tags inside the div?:
<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>
Upvotes: 0
Reputation: 115242
Use previousElementSibling
to get the previous sibling element.
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>
For older browser check polyfill option.
Upvotes: 2
Reputation: 5788
Please find below snippet
$( "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>
Upvotes: 1
Reputation: 133423
You can use .prev()
to get immediately preceding sibling and then show/hide them.
$('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
Upvotes: 3