Append div to end of document with jQuery?
I would like to write a fun开发者_如何学编程ction 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?
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>');
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
.
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);
精彩评论