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
  • 29,986
  • 58
  • 187
  • 303

3 Answers3

48

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
  • 224,675
  • 49
  • 309
  • 312
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
  • 146,912
  • 75
  • 297
  • 349
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,037
  • 6
  • 23
  • 48