2011-07-27 22 views

Respuesta

190

var div = document.createElement("div"); 
 
div.style.width = "100px"; 
 
div.style.height = "100px"; 
 
div.style.background = "red"; 
 
div.style.color = "white"; 
 
div.innerHTML = "Hello"; 
 

 
document.getElementById("main").appendChild(div);
<body> 
 
<div id="main"></div> 
 
</body>

var div = document.createElement("div"); 
div.style.width = "100px"; 
div.style.height = "100px"; 
div.style.background = "red"; 
div.style.color = "white"; 
div.innerHTML = "Hello"; 

document.getElementById("main").appendChild(div); 
OR 
document.body.appendChild(div); 

Uso de referencia de los padres en lugar de document.body.

8

esta solución utiliza la biblioteca jQuery

$('#elementId').append("<div class='classname'>content</div>"); 
+3

Curioso buscando Javascript. – TheCarver

40

depende de cómo lo está haciendo. javascript puro:

var div = document.createElement('div'); 
div.innerHTML = "my <b>new</b> skill - <large>DOM maniuplation!</large>"; 
// set style 
div.style.color = 'red'; 
// better to use CSS though - just set class 
div.setAttribute('class', 'myclass'); // and make sure myclass has some styles in css 
document.body.appendChild(div); 

Hacer lo mismo usando jQuery es convirtiera fácilmente:

$('body') 
.append('my DOM manupulation skills dont seem like a big deal when using jquery') 
.css('color', 'red').addClass('myclass'); 

Salud!

+3

No diría que jQuery es más fácil, es más corto. Pero, en lugar de usar setAttribute para la clase, usaría div.className = 'myclass'; –

+4

jQuery es MUCHO más fácil una vez que comienzas a desarrollar pesadas IU de JavaScript. dado que abarca el modelo funcional de programación desde el principio, hace que su código luzca y se comporte funcionalmente también. Caso en cuestión: ajax usando js nativo vs jquery :) – jrharshath

+3

Llamar a jQuery "funcional" es un tramo importante. ¿Cómo defines el modelo funcional y de qué manera crees que jQuery lo abraza? –

4

Aquí hay una solución que me gustaría usar:

var div = '<div id="yourId" class="yourClass" yourAttribute="yourAttributeValue">blah</div>'; 

Si quería el atributo y/o valores de atributos que se basa en las variables:

var id = "hello"; 
var classAttr = "class"; 
var div = '<div id='+id+' '+classAttr+'="world" >Blah</div>'; 

Entonces, para anexar al cuerpo :

document.getElementsByTagName("body").innerHTML = div; 

Easy as pie.

+0

¿Qué debo escribir en la página html? –

+0

La parte superior es HTML ... – Peter

4

Mientras otras respuestas funcionan, noto que ha solicitado un div con contenido. Así que aquí está mi versión con contenido adicional. Enlace JSFiddle en la parte inferior.

JavaScript(con comentarios) :

// Creating a div element 
var divElement = document.createElement("Div"); 
divElement.id = "divID"; 

// Styling it 
divElement.style.textAlign = "center"; 
divElement.style.fontWeight = "bold"; 
divElement.style.fontSize = "smaller"; 
divElement.style.paddingTop = "15px"; 

// Adding a paragraph to it 
var paragraph = document.createElement("P"); 
var text = document.createTextNode("Another paragraph, yay! This one will be styled different from the rest since we styled the DIV we specifically created."); 
paragraph.appendChild(text); 
divElement.appendChild(paragraph); 

// Adding a button, cause why not! 
var button = document.createElement("Button"); 
var textForButton = document.createTextNode("Release the alert"); 
button.appendChild(textForButton); 
button.addEventListener("click", function(){ 
    alert("Hi!"); 
}); 
divElement.appendChild(button); 

// Appending the div element to body 
document.getElementsByTagName("body")[0].appendChild(divElement); 

HTML:

<body> 
    <h1>Title</h1> 
    <p>This is a paragraph. Well, kind of.</p> 
</body> 

CSS:

h1 { color: #333333; font-family: 'Bitter', serif; font-size: 50px; font-weight: normal; line-height: 54px; margin: 0 0 54px; } 

p { color: #333333; font-family: Georgia, serif; font-size: 18px; line-height: 28px; margin: 0 0 28px; } 

Nota: Las líneas de CSS tomados de Ratal Tomal

jsFiddle:https://jsfiddle.net/Rani_Kheir/erL7aowz/

2

Se pueden crear como esto

board.style.cssText = "position:fixed;height:100px;width:100px;background:#ddd;" 

document.getElementById("main").appendChild(board); 

completa Ejecutable Fragmento:

var board; 
 
board= document.createElement("div"); 
 
board.id = "mainBoard"; 
 
board.style.cssText = "position:fixed;height:100px;width:100px;background:#ddd;" 
 
    
 
document.getElementById("main").appendChild(board);
<body> 
 
<div id="main"></div> 
 
</body>

Cuestiones relacionadas