Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

400
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!