user3149979 user3149979 - 2 months ago 14
Javascript Question

How to make getElementsByClassName do changes to all elements?

I am new to javascript, I want to apply changes to all the elements with the same class name but I can only get my script to make the changes to the first element.

This is my script. Thanks in advance.

function ReadMore(){
var txt = document.getElementsByClassName('pa')[0].innerHTML;


var btn=document.createElement("BUTTON");
var t=document.createTextNode("...");
btn.appendChild(t);
btn.onclick = function(){
document.getElementsByClassName("pa")[0].innerHTML= txt;
};

if (txt.length > 350){
var split = txt.slice(0, 50);
document.getElementsByClassName("pa")[0].innerHTML= split;
document.getElementsByClassName("pa")[0].appendChild(btn);
}}

Answer

Here is a way to write your code i only change your code for a loop and i don't know what do you want to do with your elements but if you want to do it for all items you can use this code

function ReadMore(){  

   var elements = document.getElementsByClassName('pa');

   for (var i = 0; i < elements.length; ++i) {  
       var item = elements[i];    
       var txt = item.innerHTML;
       var btn = document.createElement("BUTTON");
       var t = document.createTextNode("...");

       btn.appendChild(t);
       btn.onclick = function(){
         item.innerHTML= txt;
       };

       if (txt.length > 350){
           var split = txt.slice(0, 50); 
           item.innerHTML = split;
           item.appendChild(btn);      
       }    
}}