Recently, I started learning javascript and I am attempting to use vanilla javascript to show and hide text on click. However, I can't seem to figure out what is going wrong. Here is the code snippet I have:
Below is the HTML code snippet:
<p class="h5 font-weight-normal">some text<span id="toggle-content" class="toggle-
content" aria-hidden="true">some other text</span></p>
<a class="text-danger toggle-button" aria-controls="toggle-content">show more</a>
Here is the javascript code snippet:
const a = document.querySelector('.toggle-button');
if(a) {
a.addEventListener('click', () => {
const content = document.querySelector('.toggle-content');
const ariaHidden = content.getAttribute('aria-hidden');
content.setAttribute('aria-hidden', ariaHidden === 'true' ? 'false' : 'true');
const buttonText = content.getAttribute('aria-hidden') === 'true' ? 'Show' : 'Hide';
a.innerHTML = `${buttonText} more`;
});
}
And finally, this is the CSS code snippet:
.toggle-content {
display: none;
}
.toggle-content[aria-hidden="false"] {
display: block;
}