document.getElementsByTagName() not working properly

i was trying to change all the element by using document.getElementsByTagName() method but it was not working. I was using a for loop

function fun(idorclass,index){
   if(idorclass != null){
     return document.getElementsByTagName(idorclass)[index];
   }
   else{
    var fwe = document.getElementsByTagName(x);
    for (let i = 0; i < fwe.length; i++) {
      return fwe[i];
   }
}
}
fun('p').innerHTML='hi';
<p>hey</p><br>
<p>hey</p><br>
<p>hey</p><br>
<p>hey</p><br>

i was able to see an error that was ‘Uncaught TypeError: Cannot set properties of undefined.’ please help!