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

410
Vistas
Why does the html end up below the JavaScript link when element appended?

my question is that I am using jQuery in JavaScript and using detach and append. Here is my JavaScript append and detach script.

var example1 = $(".example1").detach();
var example2 = $(".example2").detach();

showexample2();

$("#blue").click(function(){
    alert("hi");
    showexamples2();
    hideexamples1();
});


$("#red").click(function(){
    hideexamples2();
    showexamples1();
});



function hideexamples2(){
    $(".example2").detach();
}

function showexample2s(){
    $("body").append(example2);
}

function hideexamples1s(){
    $(".example1").detach();
}

function shoexamples1s(){
    $('body').append(example1);
}

However when red is clicked it ends up below the JavaScript and therefore has no functionality. enter image description here

How can I fix this?

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

0

You are appending the element to the body. Which means it is being appended at the end of the body tags content. Use a explicit selector if you want to append it elsewhere like and ID or a class.

$('#elementToAppendTo').append(example1);

EDIT: Took me a while to understand the second half of your request. For the appended element to respond to events you need to attach the event listener on the parent. So that the event bubbles up through the DOM stack and your click event fires.

$("body").on("click", "#blue", function(){
    alert("hi");
    showexamples2();
    hideexamples1();
});

$("body").on("click", "#red", function(){
    hideexamples2();
    showexamples1();
});

This way your events will work even when you remove and re-add the DOM elements. I recommend consulting the jQuery documentation further.

EDIT:
To further iterate I recommend not putting script tags with code like that, put your javascript in an external file, and reference to it via a script source tag.

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