Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

159
Visualizações
Javascript dynamically created Divs

This is a simple javascript code. I'm creating 5 divs in script and populate an 'onclick' event for each. However, all of them give me the id of the last one. Any idea why this behavior occurring? Many thanks.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Test Page</title>
    <style type="text/css">
        .divImgPoint {
            float: left;
            border-radius: 50%;
            width: 15px;
            height: 15px;
            margin-left: 5px;
            margin-right: 5px;
            border: ridge 2px #c73756;
        }

        .divTest {
            position: absolute;
            width: 100px;
            height: 100px;
            top: 200px;
            left: 100px;
            border: 1px solid red;
        }
    </style>
    <script type="text/javascript">
        function createNewDivs() {
            var divFixed = document.getElementById('divFixed');
            var newDiv;

            for (xI = 0; xI < 5; xI++) {
                newDiv = document.createElement('div');
                newDiv.id = "newDiv_" + xI;
                newDiv.className = "divImgPoint";
                newDiv.onclick = () => { alert(newDiv.id + " | " + xI); }
                divFixed.appendChild(newDiv);
            }
        }
    </script>
</head>
<body>
    <div id="divFixed">
    </div>
</body>
</html>
<script type="text/javascript">
    window.addEventListener('load', () => { createNewDivs(); });
</script>

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Put let newDiv; inside loop.

Like

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Test Page</title>
    <style type="text/css">
        .divImgPoint {
            float: left;
            border-radius: 50%;
            width: 15px;
            height: 15px;
            margin-left: 5px;
            margin-right: 5px;
            border: ridge 2px #c73756;
        }

        .divTest {
            position: absolute;
            width: 100px;
            height: 100px;
            top: 200px;
            left: 100px;
            border: 1px solid red;
        }
    </style>
    <script type="text/javascript">
        function createNewDivs() {
            var divFixed = document.getElementById('divFixed');
            

            for (xI = 0; xI < 5; xI++) {
                let newDiv;
                newDiv = document.createElement('div');
                newDiv.id = "newDiv_" + xI;
                newDiv.className = "divImgPoint";
                newDiv.onclick = () => { alert(newDiv.id + " | " + xI); }
                divFixed.appendChild(newDiv);
            }
        }
    </script>
</head>
<body>
    <div id="divFixed">
    </div>
</body>
</html>
<script type="text/javascript">
    window.addEventListener('load', () => { createNewDivs(); });
</script>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda