Question Looping through an array in JavaScript

asest

Member
Joined
Aug 25, 2010
Messages
7
Location
Kent, UK
Programming Experience
1-3
I am trying to set a array of elements to a certain style and for various reasons I need to do this in JavaScript.

Can anyone tell me what might be wrong with the loop below? I am not too experienced with arrays or loops but am sure I just need a subtle alteration to the code.

Thank you in anticpation.

function setStyle() {
var p1 = document.getElementById('Prince1');
var p2 = document.getElementById('Prince2');
var p = new Array(p1, p2);
for (var i in p) {
i.style.color = '#4444ff';
i.style.textDecoration = "underline";
}
}
 
Looping through an Array is JS

I think your issue is that i is not the object as in .Net it is the Key in JS.

You will need to get the object using the key first as below.

function setStyle() {
var p1 = document.getElementById('Prince1');
var p2 = document.getElementById('Prince2');
var p = new Array(p1, p2);
for (var i in p) {
p.style.color = '#4444ff';
p.style.textDecoration = "underline";
}
} .
 
Back
Top