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

402
Visualizações
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 Respostas
Responde à pergunta

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 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