you can add a class to the container of both elements to change both of their statuses together.
Here, I add the class less-mode to the container to both show the text inside the textArea and change the button to show less instead of show more.
Instead of saving the state in the javascript, we can know the state by checking if the class already exists on the container.
There are two "modes":
- when
container has the class less-mode, make textArea display: block to show it, and show the less element inside the link.
- when
container doesn't have the class less-mode, make textArea display: none to hide it completely, and show the more element inside the link.
This way, most of the responsibility for the visual change lay in the CSS and HTML. the JavaScript code only switches between them
const containerElement = document.getElementById("container");
function toggleText() {
if (containerElement.classList.contains('less-mode')) {
containerElement.classList.remove('less-mode');
} else {
containerElement.classList.add('less-mode');
}
}
.more-btn .less {
display: none;
}
.more-btn .more {
display: block;
}
#textArea {
display: none;
}
.container.less-mode #textArea {
display: block;
}
.container.less-mode .more-btn .less {
display: block;
}
.container.less-mode .more-btn .more {
display: none;
}
.red {
background: red;
color: white;
padding: 5px;
}
<div class="container" id="container">
<a id="toggleButton" class="more-btn" onclick="toggleText();" href="javascript:void(0);">
<div class="more">See More</div>
<div class="less">See Less</div>
</a>
<div id="textArea">
<h3>Title</h3>
<div class="red">red text</div>
</div>
</div>
<Script>should be<script>