可以使用forEach方法遍历NodeList,并根据条件应用类。以下是一个示例代码:
const nodeList = document.querySelectorAll('.some-class');
nodeList.forEach(node => {
if (node.textContent.includes('some-text')) {
node.classList.add('new-class');
}
});
上述代码中,首先使用querySelectorAll方法获取带有类名为"some-class"的所有元素,并将其存储在nodeList变量中。然后,使用forEach方法遍历nodeList中的每个元素。在遍历过程中,如果元素的textContent属性包含"some-text",则使用classList.add方法将新的类"new-class"应用于该元素。
上一篇:遍历NodeList并删除元素