0

the code below cannot run properly on Google Chrome :

var e,
    divStyle = {
        backgroundColor: "rgba(153, 153, 153, 0.29)",
        postion: "fixed",
        top: 0,
        left: 0,
        width: "100%",
        height: "100%"
    },
    imgStyle = {
        maxWidth: "700px",
        maxHeight: "700px"
    },
    imgDivs = document.getElementsByClassName("resumeAttchImg"),
    listener = function () {
        var style,
            img = this.firstElementChild;
        for (style in divStyle)
            this.style[style] = divStyle[style];
        for (style in imgStyle)
            img.style[style] = imgStyle[style];
    };
for (e in imgDivs) {
    imgDivs[e].addEventListener("click", listener);
    console.log(imgDivs[e].addEventListener);
}

Chrome threw an exception:

"Uncaught TypeError: imgDivs[e].addEventListener is not a function"

how ever, console.log(imgDivs[e].addEventListener) do print a function definition like :

function test.html:182 addEventListener() { [native code] }

how to fix this?

Niklesh Raut
  • 34,013
  • 16
  • 75
  • 109
wangkaibule
  • 808
  • 1
  • 9
  • 20
  • 1
    Use a normal `for` loop, not a `for...in` loop to iterate over a `NodeList`. – Felix Kling Mar 05 '16 at 02:25
  • why are you using a `for in` loop? use either a regular loop, native forEach, or reverse while. – EasyBB Mar 05 '16 at 02:26
  • To add to @FelixKling's comment, consider reading [this StackOverflow post about `for..in vs for](http://stackoverflow.com/questions/5263847/javascript-loops-for-in-vs-for) – Nick Zuber Mar 05 '16 at 02:37
  • Just to know, why does it respond only on for loop? Because on a lesson I sow online, they did it without it - like this: var btn = document.getElementsByTagName("button"); btn.addEventListener("click", function(){ document.body.style.backgroundColor = "pink"; }); – Nadav Himmelfarb May 29 '18 at 19:54
  • 1
    @NadavHimmelfarb I was trying to apply the same styles to a list of elements instead of single one, so the `for` loop helps to keep the code clean. However, the `for in` loop iterates all elements in the return value of `getElementsByClassName` which is a `NodeList` type containing extra properties than simply node elements. – wangkaibule May 29 '18 at 23:07

0 Answers0