简体   繁体   中英

How do I change multiple anchor tag text using Javascript?

I have this anchor tag seven times in my html page:

<a class="collapsible" style="cursor: pointer;"><span>read more</span></a>

and script is like this:

var coll = document.getElementsByClassName("collapsible");
var i;

for (i = 0; i < coll.length; i++) {
  coll[i].addEventListener("click", function() {
    this.classList.toggle("active");
    var content = this.previousElementSibling;
    if (content.style.display === "block") {
      content.style.display = "none";
      coll[i].innerText="read more";    //if I use coll[0] then it works for first element, but I want to use it for multiple elements
    } else {
      content.style.display = "block";
      coll[i].innerText="read less";
    }
  });
}
var coll = document.getElementsByClassName("collapsible");
var i;

for (i = 0; i < coll.length; i++) {
  coll[i].addEventListener("click", function() {
    this.classList.toggle("active");
    var content = this.previousElementSibling;
    if (content.style.display === "block") {
      content.style.display = "none";
      this.innerText="read more";
    } else {
      content.style.display = "block";
      this.innerText="read less";
    }
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM