在一行中设置DOM属性



是否可以将以下内容重写为单个表达式?我喜欢用vanilla js编写代码,并希望使我的代码不那么冗长

const div = document.createElement("div");
div.property1 = 1,
div.property2 = 2,
document.body.appendChild(div);

您可以,但代价是创建另一个对象并通过Object.assign:循环其属性

document.body.appendChild(Object.assign(document.createElement("div"), {property1: 1, property2: 2}));

带换行符:

document.body.appendChild(
Object.assign(
document.createElement("div"),
{property1: 1, property2: 2}
)
);

无偿的实例:;-(

document.body.appendChild(
Object.assign(
document.createElement("div"),
{
className: "example",
id: "ex",
textContent: "Hi there"
}
)
);
.example {
color: green;
}
#ex {
font-weight: bold;
}

用于insterest。根据T.J的回答,如果使用助手函数,您可以获得更少的详细信息:
body.ac(as(ce("div"), { property1: 1, property2: 2 }));

最新更新