Coding⏱️ 1 min read📅 2026-05-31

How to Fix: JavaScript click handler not working as expected inside a for loop

The issue is caused by the variable i being scoped to the for loop, not the global scope. To fix this, use let or const instead of var.

Quick Answer: Use let or const instead of var to declare i.

The problem lies in the way you're using the jQuery library. The '$' symbol is not a valid way to call the jQuery function. Instead, you should use the '.click()' method directly on the element.

✅ Fixing the Code

  • Replace '$("#div" + i).click(')' with '.click(function(){})' on each iteration of the loop.

Here's an example:

Corrected Code

  1. Step 1: Replace '$("#div" + i).click(')' with '.click(function(){})' on each iteration of the loop.

For example:

for (var i = 1; i < 6; i++) {
console.log(i);$('#div' + i).click(function() { alert(i);});}

Did this fix your problem?

If not, try searching for specific error codes.

🔍 Search Error Database

❓ Frequently Asked Questions