¿Cómo puedo usar JavaScript para crear y diseñar (y agregar a la página) un div, con contenido? Sé que es posible, pero ¿cómo?
¿Cómo puedo usar JavaScript para crear y diseñar (y agregar a la página) un div, con contenido? Sé que es posible, pero ¿cómo?
Respuestas:
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);
Use la referencia principal en lugar de document.body.
Depende de cómo lo estés 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 vergonzosamente fácil:
$('body')
.append('my DOM manupulation skills dont seem like a big deal when using jquery')
.css('color', 'red').addClass('myclass');
¡Salud!
divpor lo tanto, no responde la pregunta
Si bien otras respuestas aquí funcionan, noté que solicitó un div con contenido. Así que aquí está mi versión con contenido extra. 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: líneas CSS prestadas de Ratal Tomal
Aquí hay una solución que usaría:
var div = '<div id="yourId" class="yourClass" yourAttribute="yourAttributeValue">blah</div>';
Si desea que el atributo y / o los valores de atributo se basen en variables:
var id = "hello";
var classAttr = "class";
var div = '<div id='+id+' '+classAttr+'="world" >Blah</div>';
Luego, para anexar al cuerpo:
document.getElementsByTagName("body").innerHTML = div;
Muy fácil.
[0]cuándo usar getElementsByTagName(). (Demasiado corto para una edición)
Puedes crear así
board.style.cssText = "position:fixed;height:100px;width:100px;background:#ddd;"
document.getElementById("main").appendChild(board);
Fragmento Runnable completo:
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>
crear div con nombre de identificación
var divCreator=function (id){
newElement=document.createElement("div");
newNode=document.body.appendChild(newElement);
newNode.setAttribute("id",id);
}
agregar texto a div
var textAdder = function(id, text) {
target = document.getElementById(id)
target.appendChild(document.createTextNode(text));
}
código de prueba
divCreator("div1");
textAdder("div1", "this is paragraph 1");
salida
this is paragraph 1
Otra cosa que me gusta hacer es crear un objeto y luego pasar por el objeto y configurar los estilos de esa manera porque puede ser tedioso escribir cada estilo uno por uno.
var bookStyles = {
color: "red",
backgroundColor: "blue",
height: "300px",
width: "200px"
};
let div = document.createElement("div");
for (let style in bookStyles) {
div.style[style] = bookStyles[style];
}
body.appendChild(div);