2011-07-11 16 views
15

Me gustaría escribir una función usando jQuery para anexar un div al final de una página web. Me gustaría poder usar la función en muchas páginas diferentes.¿Añadir div al final del documento con jQuery?

He escrito el código siguiente, pero no funciona:

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

¿Cómo puedo solucionar esto?

+5

Use '$ (document.body)'. –

+0

Creo que es porque lo anexas directamente al documento. Intenta agregarlo a $ ('body') – HumanCatfood

+0

¡Gracias chicos! ¡Este sitio me ahorra tanto tiempo y frustración! –

Respuesta

39

No tiene sentido adjuntar al document. Anexar al nodo del documento body lugar, ya que es donde todo el contenido visible es:

$(document.body).append('<div id="helloDiv"></div>'); 
7

Si usted quiere que sea al final de la body, por qué no usar:

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

http://jsfiddle.net/ptuxX/

Sin embargo, solo .css('top', 100) no hace mucho a menos que configure el position en absolute.

+2

y debe ser .css ('top', 100) sin comillas o .css ('top', '100px') –

+0

@Hierow: tienes razón, gracias. – pimvdb

0

Probar:

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

O simplemente añada el contenido y es css antes de añadir el div.

var $newdiv = '<div id="helloDiv">hello</div>'; 
$('body').append($newdiv);