Dirty Bird Design
Dirty Bird Design

Reputation: 5523

How to append dynamically created div to container

I need to display a message from the server (log out) in a dynamic div. I can get it to work if I have the div element coded into the page as such:

<div id="message"></div>

with the css #message{display:none;} using this js

$('#LogOut').on('click', function(e){
    $.ajax({
        type: "POST",
        url: "PHP/LogOut.php",
        success: function(data) {
        $('#message').fadeIn('fast').html('<p><span>Somesite.com</span>' + data + '<a id="close" href="">X</a></p>');
      }
    });
    e.preventDefault();
  });

I cannot get this to work with .append, I don't want to have to hard code the on each page. Is there a good way to create this dynamically and append to div#main on each and every page when you click log out? I have no issues other than this, PHP is fine, log out works fine etc... thank you.

Upvotes: 1

Views: 1448

Answers (1)

plalx
plalx

Reputation: 43718

Try using appendTo:

$('<div id="message"></div>').appendTo(document.body).html('<p><span>Somesite.com</span>' + data + '<a id="close" href="">X</a></p>').fadeIn('fast');

The thing with append is that it doesn't return the appended element, it keeps returning the parent element.

$(document.body).append($('<div></div>')) //returns $(document.body);

Upvotes: 3

Related Questions