我如何使用JavaScript创建和风格(并追加到页面)一个div,与内容? 我知道这是可能的,但怎么做呢?


当前回答

下面是一个小例子,它使用了一些漂亮的可重用DOM实用函数:

// DOM utility functions: const ELNew = (tag, prop) => Object.assign(document.createElement(tag), prop), ELS = (sel, par) => (par ?? document).querySelectorAll(sel), EL = (sel, par) => (par ?? document).querySelector(sel); // Task: const EL_new = ELNew("div", { className: "item", textContent: "Hello, World!", onclick() { console.log(this.textContent); }, style: ` font-size: 2em; color: brown; background: gold; ` }); // Append it EL("body").append(EL_new);

此外,你还可以使用Object.assign()对元素进行样式化,如下所示:

// Add additional styles later:
Object.assign(EL_new.style, {
  color: "red",
  background: "yellow",
  fontSize: "3rem",
});

其他回答

你可以这样做

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

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

完整的可运行代码片段: var董事会; 董事会= document.createElement (" div "); 董事会。id = "主板"; board.style.cssText = "位置:固定;高度:100px;宽度:100px;背景:#ddd;" . getelementbyid(“主要”).appendChild(板); 身体< > < div id = "主" > < / div > 身体< / >

var div = document.createElement("div"); Div.style.width = "100px"; Div.style.height = "100px"; Div.style.background = "red"; Div.style.color = "白色"; div.innerHTML = "Hello"; . getelementbyid(“主要”).appendChild (div); 身体< > < div id = "主" > < / div > 身体< / >

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);

使用父引用而不是document.body。

创建id为name的div

var divCreator=function (id){
newElement=document.createElement("div");
newNode=document.body.appendChild(newElement);
newNode.setAttribute("id",id);
}

向div添加文本

var textAdder = function(id, text) {
target = document.getElementById(id)
target.appendChild(document.createTextNode(text));
}

测试代码

divCreator("div1");
textAdder("div1", "this is paragraph 1");

输出

this is paragraph 1

这将在一个自定义CSS的函数或脚本标记中,类名为custom

 var board = document.createElement('div');
 board.className = "Custom";
 board.innerHTML = "your data";
 console.log(count);
 document.getElementById('notification').appendChild(board);

这个解决方案使用jquery库

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