简体   繁体   English

为什么 Array.from(classList)[0] = "className" 不起作用

[英]Why Array.from(classList)[0] = "className" not work

Html code Html代码

<div class="container color-blue">
        <h3>HI I am a container</h3>
    </div>

js code js代码

let div =document.getElementsByClassName('container')[0];
let a = div.classList;
// here is a is an object 
// so I use array.from(a) to turn in into array 
Array.from(a)[0] = "font";

"arrays are mutable and array can be chnaged" but it not replacing my container that is the first item of array with font “数组是可变的,数组可以更改”,但它没有用字体替换我的容器,它是数组的第一项

Array.from will create a new array from classList which is an instance of DOMTokenList . Array.from将从classList创建一个新数组,它是DOMTokenList的一个实例。

If you must remove the first item do如果您必须删除第一项,请执行

let div =document.getElementsByClassName('container')[0];
let a = div.classList;
a.remove(a.item(0))

You can then just add the item you need然后,您可以添加您需要的项目

a.add("font");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM