Как по клику добавить класс?
На странице есть блок комментарий, по нажатию на кнопку ответить нужно показать форму, где будет вводиться ответ, если форма показана и пользователь нажал на другом комментарии кнопку ответить, активную форму нужно скрыть и показать в другом месте. Как это можно сделать?
.comment {
width: 100%;
}
.comment-item {
max-width: 350px;
margin: 0 auto;
margin-bottom: 50px;
}
.comment-item__text {
font-weight: bold;
font-size: 20px;
margin-bottom: 10px;
}
.comment-item__reply {
margin-bottom: 15px;
cursor: pointer;
}
.comment-item__form {
display: none;
}
<div class="comment">
<div class="comment-item">
<div class="comment-item__text">Комментарий</div>
<div class="comment-item__reply">Ответить</div>
<div class="comment-item__form">
<form action="">
<textarea name="" id="" cols="30" rows="5" class="" placeholder="Ваш комментарий"></textarea>
</form>
</div>
</div>
<hr>
<div class="comment-item">
<div class="comment-item__text">Комментарий</div>
<div class="comment-item__reply">Ответить</div>
<div class="comment-item__form">
<form action="">
<textarea name="" id="" cols="30" rows="5" class="" placeholder="Ваш комментарий"></textarea>
</form>
</div>
</div>
</div>
Ответы (1 шт):
Автор решения: VanilJS
→ Ссылка
let allCommentItem = document.querySelectorAll('.comment-item');
allCommentItem.forEach(commentItem => {
commentItem.querySelector('.comment-item__reply').addEventListener('click', e => {
allCommentItem.forEach(i => i.querySelector('.comment-item__form').classList.remove('visible'))
commentItem.querySelector('.comment-item__form').classList.add('visible')
})
})
.comment {
width: 100%;
}
.comment-item {
max-width: 350px;
margin: 0 auto;
margin-bottom: 50px;
}
.comment-item__text {
font-weight: bold;
font-size: 20px;
margin-bottom: 10px;
}
.comment-item__reply {
margin-bottom: 15px;
cursor: pointer;
}
.comment-item__form {
display: none;
}
.visible {
display: block
}
<div class="comment">
<div class="comment-item">
<div class="comment-item__text">Комментарий</div>
<div class="comment-item__reply">Ответить</div>
<div class="comment-item__form">
<form action="">
<textarea name="" id="" cols="30" rows="5" class="" placeholder="Ваш комментарий"></textarea>
</form>
</div>
</div>
<hr>
<div class="comment-item">
<div class="comment-item__text">Комментарий</div>
<div class="comment-item__reply">Ответить</div>
<div class="comment-item__form">
<form action="">
<textarea name="" id="" cols="30" rows="5" class="" placeholder="Ваш комментарий"></textarea>
</form>
</div>
</div>
</div>