I want to add a CSS
class name to the next sibling of an element as soon as I click on it to get a simple show/hide effect
I have the following html output and I don't have element-ID's.
<div class="news-message">
<div class="message-head"> Headline of Message 1 </div>
<div class="message-content"> Here comes the content of message 1 </div>
</div>
<div class="news-message">
<div class="message-head"> Headline of Message 2 </div>
<div class="message-content"> Here comes the content of message 2 </div>
</div>
<div class="news-message">
<div class="message-head"> Headline of Message 3 </div>
<div class="message-content"> Here comes the content of message 3 </div>
</div>
Now I want to hide the message-content and just display the headline (easy to realize with display: none
).
As soon as I click on the headline, I want the content of that specific message to be displayed.
So my idea was to add a CSS
class "visible" to the DIV
"message-content" by click on message-head and remove it by another click.
So I added a "onClick="changeClass()" to the "pm-head" Element and the following javascript
function changeClass() {
var hidecontent = document.querySelectorAll('.message-content');
var i;
for (i = 0; i < hidecontent.length; i++) {
hidecontent[i].classList.toggle('visible'); } }
but this adds the class visible to all "message-content" divs on that page while I just need it to be added to the next sibling of the "pm-head" element on which I have clicked.
And I can´t use jquery or other frameworks/libraries on this one.
Sorry, I am new to javascript, probably an easy to answer question.
Thanks John