Kindly check given code I need to hide "description box" (red border box) on the click
of "hide this" button. I have select all button by using loop and also added on click function
by using "add event listener". But am unable to hide it’s sibling. please help me to achieve this.
var hideBtn, i;
hideBtn = document.getElementsByClassName('hide-this');
for (i = 0; i < hideBtn.length; i++) {
hideBtn[i].addEventListener('click', function() {
alert('Hello');
})
}
.hide-this {
background: red;
padding: 10px;
width: 100px;
display: block;
width: 100px;
}
.description {
border: 1px solid red;
padding: 10px;
width: 100px;
margin-bottom: 20px;
}
<a class="hide-this">Hide This</a>
<div class="description">
This is our description
</div>
<a class="hide-this">Hide This</a>
<div class="description">
This is our description
</div>
<a class="hide-this">Hide This</a>
<div class="description">
This is our description
</div>
>Solution :
You were good, just have to use nextElementSibling to change display to ‘none’
var hideBtn, i;
hideBtn = document.getElementsByClassName('hide-this');
for(i=0; i<hideBtn.length; i++){
hideBtn[i].addEventListener('click', function(){
if(this.nextElementSibling.style.display == 'none')
this.nextElementSibling.style.display = 'block'
else
this.nextElementSibling.style.display = 'none'
})
}
.hide-this{
background:red;
padding:10px;
width:100px;
display: block;
width:100px;
}
.description{
border:1px solid red;
padding: 10px;
width:100px;
margin-bottom: 20px;
}
<a class="hide-this">Hide This</a>
<div class="description" >
This is our description
</div>
<a class="hide-this">Hide This</a>
<div class="description">
This is our description
</div>
<a class="hide-this">Hide This</a>
<div class="description">
This is our description
</div>