I have 2 buttons on a page, "read more" and a "read less", which are created using a Page Builder in WP. I am trying to hide all elements after the Read More button when the page loads. Once the button is clicked I want the "Read More" to display: none; and then every element that was hidden after the "Read More" button to be visible and then that button be hidden while the "Read Less" button is then visible and vice versa.
So far I have this code which will display the parent and then all siblings excluding the element that I want as the starting point. I’ve watched a bunch of videos and I am sure there’s an easier way to achieve this but it has to be done this certain way.
const readMore = document.getElementById("read-more");
const readLess = document.getElementById("read-less");
var getSiblings = function(elem) {
// Setup siblings array and get the parent
var siblings = [];
var sibling = elem.parentNode.firstChild;
// Loop through each sibling and push to the array
while (sibling) {
if (sibling.nodeType === 1 && sibling !== elem) {
siblings.push(sibling);
}
sibling = sibling.nextSibling;
}
return siblings;
};
<body>
<div>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quaerat, ex.
</div>
<div>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quaerat, ex.
</div>
<div class=".et_pb_button_0_wrapper">
<button>
<a href="#" target="_blank" id="read-more">READ MORE</a>
</button>
</div>
<div>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quaerat, ex.
</div>
<div>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quaerat, ex.
</div>
<div>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quaerat, ex.
</div>
<div>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quaerat, ex.
</div>
<div>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quaerat, ex.
</div>
<div>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quaerat, ex.
</div>
<div>
<button>
<a href="#" target="_blank" id="read-less">READ LESS</a>
</button>
</div>
</body>
2
Answers
A sprinkling of CSS here, alongside your JS, will do wonders:
This snippet declares that:
.read-more
button has the.activated
class it will not display.read-more
button does not have the.activated
class, all<p>
or<button>
elements which follow it (as subsequent siblings) will not displayThen, all your JavaScript needs to deliver is:
.read-more
button is clicked, the.activated
class is added to the.read-more
button; and.read-less
button is clicked, the.activated
class is removed from the.read-more
button.Working Example:
First, there is no need for a link placed inside a button.
Second, one does not even need to classify the
<div/>
wrapper around the "READ MORE" button.One can achieve what the OP is looking for with a minimum effort solution which does not involve any class-name but which
:has()
pseudo-classdisabled
state.The implementation then comes with a footprint as small as follows …