Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

177
Vistas
How to find a subelement of a node, which is not attached to the dom?

I use jquery and es6 template strings to create a checkbox with a label:

function createCheckBx(id, text) {
        return $(`<div>
                    <input id ="${id}" type="checkbox"/>
                    <label for="${id}">${text}</label>
                 </div>`);
}

Now I would like to attach an eventlistener to the checkbox

checkBox = createCheckBx("42", "Answer");
cb.???.addEventListener("change", (evt) => {
  // do smth. when toggled
})

but the div is not attached to the dom yet so I can't use document.getElementById (or jquery's $("#...") and I don't want to access it by any kind of index like cb.childNodes[0], since the caller can't know the index and the html structure may change. Any help?

kindly regards, AJ

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Just because the element doesn't yet exist in the DOM doesn't mean you can't attach an event handler to it. The only issue in your example is the syntax you're using as you're mixing jQuery and plain JS methods. You should stick to one or the other.

As you're including jQuery in the page, here's how to make your example work:

let createCheckBox = text => $(`<div><label><input type="checkbox" />${text}</label></div>`);

let $checkBox = createCheckBox("Answer");
$checkBox.on('change', e => {
  console.log(`Checkbox checked? ${e.target.checked}`);
});

// add the checkbox to the DOM at some point:
$('body').append($checkBox);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>

Note that I removed the id attribute from the function which creates the element and also the HTML it generates. This is because creating id at runtime is an anti-pattern and should be avoided. Use common classes instead.

Also note that you may be better served by creating a single delegated event handler to handle all your dynamically appended content, instead of attaching an event as you create the new elements. Here's an example of how to do this:

let createCheckBox = text => $(`<div><label><input type="checkbox" />${text}</label></div>`);
let $container = $('.checkbox-container');

$('button').on('click', e => $container.append(createCheckBox("Answer")));

$container.on('change', ':checkbox', e => {
  console.log(`Checkbox checked? ${e.target.checked}`);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<button type="button">Add</button>
<div class="checkbox-container"></div>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda