I’m new to JavaScript, so bear with me…
I have an external JavaScript document linked to my HTML (called within the head of the HTML doc).
In my JavaScript doc, I call two functions on the window.onload event:
window.onload = function() {
selected_state();
viewer();
};
function selected_state() {
var titleAr = document.getElementsByTagName("title");
var aAr = document.getElementsByTagName("a");
// Take the first element of title array. Check if it matches
// the first element of link array.
for (i = 0; i <= titleAr.length; i++) {
for (l = 0; l <= aAr.length; l++) {
if (titleAr[i].innerHTML === aAr[l].innerHTML) {
aAr[l].style.color = "#C33";
break;
}
}
}
};
function viewer() {
var imgAr = document.getElementsByTagName("img");
for (var i = 0; i < imgAr.length; i++) {
imgAr[i].onmouseover = function() {
this.style.border = "1px solid #CCC";
}
}
};
The first function runs without problems, but the second one doesn’t run. If I switch them around, so viewer() is first, then selected_state() won’t execute. I know the issue is probably something really simple logic wise… Any takers?
Looks like
selected_stateis breaking when the inner loop finishes in the outer loop’s first run; your loop condition is incorrect (must be throwing something like “index out of bounds”).Arrays use a zero-based index:
Change:
To: