0

Im only a beginner and I'm not entirely sure how to from the question I have. Whenever I click on any of the "$element", only the very last "$newDiv" changes its color.

$(function () { // Document ready 
    test(document.getElementsByClassName("test-element"));
});


function test(divs) {
    var i = 0
    var l = divs.length;

    for (i; i < l; i++) {
        var $element = $(divs[i]);
        var $newDiv = $(document.createElement("div"));
        $element.after($newDiv);

        $element.click(function () {
            $newDiv.css({ backgroundColor: "red" });
        });
    }

}

How can a tweak this so that when I click on the first "$element", the only its own "$newDiv" affected? Is there a way to get around this without using DOM selectors in the event handler?

  • tldr; There is only *one* variable called `$newDiv`. Search for "JavaScript variables in loops". – user2864740 Aug 18 '18 at 19:38
  • hey do some reasearch ,you will get it . basically $newDiv will reference to the last once because loop goes till 5 and it have last value. – Atul Aug 18 '18 at 19:41
  • good place to learn about scoped variables https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let (it's better to use `const` whenever possible, `let` when some variable changes and then you basically can forget about using `var`) – Endless Aug 18 '18 at 19:44

1 Answers1

0

I believe this is a scoping issue, which would be resolved if you could use ES6 let instead of var. If that is not an option for you, try setting scoping your $newDiv element within the click handler:

$element.click(function () {
    var currentDiv = $newDiv
    currentDiv.css({ backgroundColor: "red" });
});
Ben Steward
  • 2,338
  • 1
  • 13
  • 23