this code on any webpage. It replaces the entire contents with eight buttons. The first four are looped over using var. The next four are looped using let. Try clicking them. Is the alert what you expect?
// DO NOT USE innerHTML! This is solely to make a simple demo!
document.body.innerHTML = "<div class=\"var\"><p>var</p><button>1</button><button>2</button><button>3</button><button>4</button></div><div class=\"let\"><p>let</p><button>1</button><button>2</button><button>3</button><button>4</button></div>";
const varButtons = document.querySelectorAll(".var button");
for (var i = 1; i <= 4; i++) {
varButtons[i-1].addEventListener("click", () => alert(i));
}
const letButtons = document.querySelectorAll(".let button");
for (let i = 1; i <= 4; i++) {
letButtons[i-1].addEventListener("click", () => alert(i));
}
I still don't get the problem with innerHTML. It's awesome if you just want to insert a string html node inside the element. *I know insertAdjacentHTML exist
If you insert *any* user-generated content with innerHTML, you may be susceptible to XSS
But users on the front end can do whatever they want and insert anything anywhere. I only use them to insert content myself in a function for instance
Content from one user can XSS another user, for example
Обсуждают сегодня