Đặng Quốc Trung Đặng Quốc Trung - 24 days ago 8
HTML Question

addEventListener freeze with "for"

I'm making a Chrome extension, but when I make the script with "for" loop to change all the stype.display of Elements with the name "mode" to none but one will be display at the end of "for" loop, but when I click on the button to use it, it just freeze my tab.

This is my javascript:

var khflip = document.getElementsByName('chuyenmode')[0];
var cmodex = document.getElementsByName('mode');
var cmodei;
khflip.addEventListener('click', function () {
for (cmodei = 0; cmodei < cmodex.length; i++) {
cmodex[cmodei].style.display = "none";
}
mode[0].removeAttribute("style");
});


and this my html code:

<div name="mode" id="tfl" style="display:none">
some codes
</div>
<div name="mode" id="random" style="display:none">
some codes
</div>
<div name="mode" id="tinhtoan" style="display:none">
some codes
</div>


Please tell me was have I do wrong

EDIT: Solved.

Answer

Instead of your code, use this:

khflip.addEventListener('click', function () {
    for (cmodei = 0; cmodei < cmodex.length; cmodei++) {
        cmodex[cmodei].style.display = "none";
      }
      mode[0].removeAttribute("style");
    });

You were incrementing the variable i with i++ instead of cmodei which meant that your loop went on forever because comdei never was greater than cmodex.length