Skip to content Skip to sidebar Skip to footer

How To Add Several Read More And Read Less Buttons Through Javascript Using Getelementsbyid Or Classname?

everyone. Recently, I have been working to add 'Read More' and 'Read Less' buttons through Javascript. I am able to do that only once for one specific element by picking its ID. Bu

Solution 1:

You can toggle a class to show/hide the spans, using some CSS, like this:

document.querySelectorAll(".showmore").forEach(function (p) {
  p.querySelector("a").addEventListener("click", function () {
    p.classList.toggle("show");
    this.textContent = p.classList.contains("show") ? "Show Less" : "Show More";
  });
});
.showmore {
  font-size: 1.1em;
  margin-top: 1.5em;
}

.showmore.more, .showmore.show.dots {
  display: none
}

.showmore.show.more {
  display: inline
}

.showmorea {
  cursor: pointer;
  display: block;
  margin-top: 0.5em;
  margin-bottom: 1em;
  font-weight: bold;
}
<pclass="showmore">This is Lorem Ipsum. This is Lorem Ipsum. <spanclass="dots">...</span><spanclass="more"> This is the hidden text. This is the hidden text. </span><a>Show More</a></p><pclass="showmore">And here is a second paragraph. <spanclass="dots">...</span><spanclass="more"> This is the hidden text. This is the hidden text. </span><a>Show More</a></p>

The code first loops over all paragraphs, then grabs the <a> inside and assigns the click handler.

Post a Comment for "How To Add Several Read More And Read Less Buttons Through Javascript Using Getelementsbyid Or Classname?"