一步创建元素并分配类

jsv*_*jsv 4 javascript

我知道以下两种创建元素并为其分配类的方法:

const el = document.createElement('div');
el.classList.add('foo');
Run Code Online (Sandbox Code Playgroud)
const el = document.createElement('div');
foo.className = 'foo';
Run Code Online (Sandbox Code Playgroud)

有没有一步解决的办法?我试过

const el = document.createElement('div').classList.add('foo');
Run Code Online (Sandbox Code Playgroud)

但它不起作用。

Maj*_*awi 8

尽管通常的方法是分两步进行,但请尝试以下操作:

const el = Object.assign(document.createElement('div'), { className: 'foo' });

console.log(el);
console.log(el.className);
Run Code Online (Sandbox Code Playgroud)

  • Object.assign 令人大开眼界,但是您能说说为什么您认为“正确的方法是两步技术”吗?我想不出这有什么问题。您将具有值的属性本身添加到新对象中,就像在第二步中添加值一样? (2认同)