Come posso usare JavaScript per creare e accodare (e aggiungere alla pagina) un div, con contenuti? So che è possibile, ma come?
Come posso usare JavaScript per creare e accodare (e aggiungere alla pagina) un div, con contenuti? So che è possibile, ma come?
Risposte:
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);
Utilizzare il riferimento principale anziché document.body.
Dipende da come lo stai facendo. 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);
Fare lo stesso usando jquery è imbarazzantemente facile:
$('body')
.append('my DOM manupulation skills dont seem like a big deal when using jquery')
.css('color', 'red').addClass('myclass');
Saluti!
divquindi non risponde alla domanda
Mentre altre risposte qui funzionano, noto che hai chiesto un div con contenuti. Quindi ecco la mia versione con contenuti extra. JSFiddle link in basso.
JavaScript (con commenti):
// 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: linee CSS prese in prestito da Ratal Tomal
questa soluzione utilizza la libreria jquery
$('#elementId').append("<div class='classname'>content</div>");
Ecco una soluzione che vorrei utilizzare:
var div = '<div id="yourId" class="yourClass" yourAttribute="yourAttributeValue">blah</div>';
Se si desidera che l'attributo e / oi valori dell'attributo siano basati su variabili:
var id = "hello";
var classAttr = "class";
var div = '<div id='+id+' '+classAttr+'="world" >Blah</div>';
Quindi, per aggiungere al corpo:
document.getElementsByTagName("body").innerHTML = div;
Facile come una torta.
[0]quando si utilizza getElementsByTagName(). (Troppo breve per una modifica)
Puoi creare così
board.style.cssText = "position:fixed;height:100px;width:100px;background:#ddd;"
document.getElementById("main").appendChild(board);
Snippet eseguibile 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>
crea div con nome ID
var divCreator=function (id){
newElement=document.createElement("div");
newNode=document.body.appendChild(newElement);
newNode.setAttribute("id",id);
}
aggiungi testo a div
var textAdder = function(id, text) {
target = document.getElementById(id)
target.appendChild(document.createTextNode(text));
}
codice di prova
divCreator("div1");
textAdder("div1", "this is paragraph 1");
produzione
this is paragraph 1
Un'altra cosa che mi piace fare è creare un oggetto e poi passare in rassegna l'oggetto e impostare gli stili in questo modo perché può essere noioso scrivere ogni singolo stile uno per 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);