Question

I am trying to set attribute for an element.

the element is pulled from a class (active) and assigned a variable. The same element is pulled from a different class (topArrow) and assigned a variable.

When comparing the two variable to run an if statement the evaluate as not the same...???

console.log to see what is going on and I get this:

HTMLCollection[img.active images/a.../top.png]
HTMLCollection[]

where as on an element that does not have a class of topArrow i get this:

HTMLCollection[img.active images/a...left.png]
HTMLCollection[img.topArrow images/a.../top.png]

    var arrow = 0;

var topArrow = document.getElementsByClassName("topArrow");
var menuText = document.getElementsByClassName("menuText");
var rightArrow = document.getElementsByClassName("rightArrow");
var bottomArrow = document.getElementsByClassName("bottomArrow");
var leftArrow = document.getElementsByClassName("leftArrow");

//assign navButtons to var buttons (creates array)
var buttons = document.getElementsByClassName("navButton");

//for each instance of buttons, assign class "active" onmouseover
for(var i = 0; i < buttons.length; ++i){
    buttons[i].onmouseover = function() {
        this.className = "active";
        var arrow = document.getElementsByClassName("active");
        console.log(arrow);
        console.log(topArrow);
        changeImages();
    }
}

//for each instance of buttons, remove class "active" onmouseout
for(var i = 0; i < buttons.length; ++i){
    buttons[i].onmouseout = function () {
        this.className = "";
    };
}

function changeImages(){
    if ( arrow == topArrow ) {
        this.setAttribute("src", "images/arrows/top_o.png");
        console.log("arrow should change");
    } else {
        console.log("arrow should not change");
    }
}
Was it helpful?

Solution

you are redefining arrow in function scope, which is overshadowing global definition.

var arrow = 0;//global

var arrow = document.getElementsByClassName("active");// overshadowing assignment

Even if you fix is removing var, hence -

arrow = document.getElementsByClassName("active");// var removed

When you use document.getElementByClassName, you get an HTMLCollection, not that element even if there is one match. Matching array using == does not behave in the way you want.

To fix that use -

if(arrow[0] == toparrow[0])//assuming you have only one element with class 'active' and 'toparrow' in dom
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top