27

I would like to write a function using jQuery to append a div to the end of a web page. I would like to be able to use the function on many different pages.

I've written the following code, but it doesn't work:

    $(document).append('<div id="helloDiv"></div>');
    $('#helloDiv').html('hello'); // does nothing
    $('#helloDiv').css('top','100') // throws an error

How do I fix this?

Vivian River
  • 31,198
  • 62
  • 198
  • 313

3 Answers3

50

It is meaningless to append to the document. Append to the document's body node instead, since this is where all the visible content is:

$(document.body).append('<div id="helloDiv"></div>');
lonesomeday
  • 233,373
  • 50
  • 316
  • 318
9

If you want it to be at the end of the body, why not use:

$('body').append('<div id="helloDiv"></div>');
$('#helloDiv').html('hello');
$('#helloDiv').css('top', 100);

http://jsfiddle.net/ptuxX/

However, just .css('top', 100) does not do much unless you set the position to absolute.

pimvdb
  • 151,816
  • 78
  • 307
  • 352
0

Try:

$('body').append('<div id="helloDiv"></div>');
$('#helloDiv').html('hello');
$('#helloDiv').css('top', '100');

Or just add the content and it's css before adding the div.

var $newdiv = '<div id="helloDiv">hello</div>';
$('body').append($newdiv);
Jules
  • 7,148
  • 6
  • 26
  • 50