var arr
var collection = document.getElementsByTagName('div')
// long version
arr = Array.prototype.slice.call(collection)
// short version
arr = [].slice.call(collection)
// ES6 version
arr = [...collection]
<button class="complete-btn">
<i class="fas fa-check"></i>
</button>
<button class="trash-btn">
<i class="fas fa-trash"></i>
</button>
.fa-trash,
.fa-check {
pointer-events: none;
}
这样,点击按钮内部图标的效果就会失效
classList
的使用<div class="hot spicy pizza">🍕</div>
// grab element reference
const pizza = document.querySelector('.pizza')
// get all existing classes
console.log(pizza.classList)
// ["hot", "spicy", "pizza", value: "hot spicy pizza"]
// get first class name
console.log(pizza.classList[0]) // hot
// get total number of classes
console.log(pizza.classList.length) // 3
add()
方法The add()
method adds one or more classes to the HTML element:
pizza.classList.add('sauce', 'cheese', 'tomato')
Now, the element looks like below:
<div class="hot spicy pizza sauce cheese tomato">🍕</div>
remove()
方法The remove()
method is used to remove one or more classes from the element:
pizza.classList.remove('sauce', 'potato')
If you try to remove a class that doesn't exist, as we did in the above example, there won't be any error. JavaScript will simply ignore it.
contains()
方法The contains()
method returns true if the element contains the given class, otherwise false
:
console.log(pizza.classList.contains('cheese')) // true
console.log(pizza.classList.contains('yogurt')) // false
toggle()
方法toggle()
is an interesting method. It removes the class if it already exists, otherwise, it adds it to the collection.
Without this method, you have to manually check if the class exists using contains()
before toggling it on or off:
// manual toggle
if (pizza.classList.contains('olive')) {
pizza.classList.remove('olive')
} else {
pizza.classList.add('olive')
}
With the toggle()
method, you simply pass the name of the class which you want to toggle:
pizza.classList.toggle('olive')
The toggle()
method returns true
if the class was added, and false
if it was removed:
const status = pizza.classList.toggle('olive')
console.log(status) // true --> class was added
You can also pass a second boolean parameter to the toggle()
method to indicate whether to add the class or remove it. This will turn toggle()
into one way-only operation. If the second argument evaluates to false
, then the class will only be removed, but not added. If it evaluates to true
, then the class will only be added, but not removed.
Here is an example:
const status = pizza.classList.toggle('hot', false)
console.log(status) // false --> class was removed
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。