MST

星途 面试题库

面试题:JavaScript操作DOM的高级难度问题

假设页面结构复杂,存在多层嵌套的元素。现在要在某个特定父元素下查找所有符合特定data - attribute值的子元素,并将它们的样式进行统一修改。请用JavaScript实现,并且要考虑性能优化,说明为什么这样做能优化性能。
42.7万 热度难度
编程语言JavaScript

知识考点

AI 面试

面试题答案

一键面试
// 查找特定父元素
const parentElement = document.querySelector('#parent - id'); // 假设通过id查找父元素

// 使用getElementsByTagName获取所有子元素,相比querySelectorAll性能更好
const allChildren = parentElement.getElementsByTagName('*');

// 遍历所有子元素,查找符合特定data - attribute值的元素并修改样式
for (let i = 0; i < allChildren.length; i++) {
    const child = allChildren[i];
    if (child.dataset.someAttribute === '特定值') {
        // 修改样式
        child.style.color = 'red';
    }
}

性能优化说明

  1. 使用getElementsByTagName替代querySelectorAllgetElementsByTagName是一个实时的HTMLCollection,在查找元素时效率更高,因为它不会像querySelectorAll那样构建一个静态的NodeList。querySelectorAll需要遍历整个DOM树来构建匹配的节点列表,而getElementsByTagName可以在遍历到符合条件的元素时就进行处理,不需要预先构建完整的列表。
  2. 直接遍历getElementsByTagName返回的集合:直接遍历getElementsByTagName返回的HTMLCollection,避免了额外的数组转换操作。这样减少了内存开销和处理时间,提升了性能。