Skip to content Skip to sidebar Skip to footer

Javascript Function On Multiple Elements At One Page?

Could you please help me to figure out this situation? On my page I'm using Javascript which dynamically generates random RGB color, which is being applied to multiple elements on

Solution 1:

id is unique; you cant have several elements with the id random. use class instead.

Solution 2:

var arrays = document.body.getElementsByTagName('A');
for(var i = 0; i < arrays.length; i ++) {
    var elem = arrays[i];
    if(elem.id == 'random') {
        elem.style.color = 'rgb('+r+', '+g+', '+b+')';
    }
}

Please replace 'MM_changeProp('random','','style.color','rgb('+r+', '+g+', '+b+')'); ' with those scripts above.

Duplicated id is bad pratical. Better using class instead of id. Importing a js selector library such as jQuery is highly recommended. Then you can write just one line:

$('.random').css('color', 'rgb('+r+', '+g+', '+b+')');

Post a Comment for "Javascript Function On Multiple Elements At One Page?"