I have a javascript function that looks like that:
function myfun(){
//product.1
var t1=document.getElementById('1').innerHTML;
var link = document.getElementsByClassName(t1);
if(document.getElementsByClassName(t1).length==1){
document.getElementById(t1).innerHTML=link[0].outerHTML;
document.getElementById(t1).getElementsByTagName('a')[0].className='dsad';
}
if(document.getElementsByClassName(t1).length==2){
document.getElementById(t1).innerHTML=link[0].outerHTML+'; '+link[1].outerHTML;
var element = document.getElementById(t1).getElementsByTagName('a')[0].className='dsad';
var element2 = document.getElementById(t1).getElementsByTagName('a')[1].className='dsad';
}...
//product.2
var t2=document.getElementById('2').innerHTML;
It goes like that till if(document.getElementsByClassName(t1).length==10) and then it continues element - document.getElementById('2') and so on until it reach Element number 10. The whole script is about 700 lines and I want to reduce it somehow. I was thinking of a for loop but I don't see how I could implement this. Any suggestions?
idattribute to a function and then calling that function over and over within a loop?for loopis exactly what you're looking for. w3schools.com/js/js_loop_for.aspvar link = document.getElementsByClassName(t1);, you can then refer to that element using the variable namelink, so in the next line you can write :if(link.length==1){t1both for lookup by class and id.