当前位置:首页 > JavaScript

js实现选择器

2026-01-30 08:55:43JavaScript

实现基础选择器

使用 document.querySelectordocument.querySelectorAll 实现类似 CSS 的选择器功能。前者返回第一个匹配元素,后者返回所有匹配的 NodeList。

// 选择单个元素  
const element = document.querySelector('#id');  
const element = document.querySelector('.class');  
const element = document.querySelector('div');  

// 选择所有匹配元素  
const elements = document.querySelectorAll('.class');  

按属性选择元素

通过属性选择器定位元素,支持精确匹配或部分匹配。

js实现选择器

// 精确匹配属性  
const links = document.querySelectorAll('a[href="https://example.com"]');  

// 匹配属性包含特定值  
const icons = document.querySelectorAll('[class*="icon-"]');  

// 匹配属性以特定值开头  
const inputs = document.querySelectorAll('input[type^="text"]');  

层级与组合选择器

通过组合选择器实现更复杂的层级关系匹配。

js实现选择器

// 子元素选择  
const listItems = document.querySelectorAll('ul > li');  

// 相邻兄弟选择  
const nextButton = document.querySelector('.submit + button');  

// 通用兄弟选择  
const allSiblings = document.querySelectorAll('h1 ~ p');  

伪类与动态选择

利用伪类选择器匹配动态状态或特定位置的元素。

// 匹配悬停状态的元素(需通过事件监听实现)  
element.addEventListener('mouseover', () => {  
  element.style.color = 'red';  
});  

// 选择第一个子元素  
const firstChild = document.querySelector('li:first-child');  

// 选择第 n 个元素  
const thirdItem = document.querySelector('li:nth-child(3)');  

性能优化建议

避免频繁使用复杂选择器或全局扫描,优先通过 ID 或类名缩小范围。

// 不推荐:全局扫描  
const slow = document.querySelectorAll('div span.highlight');  

// 推荐:限定范围  
const container = document.getElementById('app');  
const fast = container.querySelectorAll('span.highlight');  

通过以上方法,可以灵活实现各种 DOM 元素选择需求。

标签: 选择器js
分享给朋友:

相关文章

js 实现链表

js 实现链表

链表的基本概念 链表是一种线性数据结构,由一系列节点组成,每个节点包含数据和指向下一个节点的指针。与数组不同,链表在内存中是非连续存储的,插入和删除操作效率较高。 链表的实现 在 JavaScrip…

js类实现

js类实现

使用类实现 JavaScript 功能 在 JavaScript 中,类(Class)是一种语法糖,基于原型继承机制。通过 class 关键字可以更直观地定义对象模板。 基本类定义 class…

js实现 功能

js实现 功能

在 JavaScript 中实现功能通常涉及多个关键步骤,具体取决于功能需求。以下是常见功能的实现方法和示例: 基本功能实现 使用函数封装逻辑是最直接的方式。例如,实现一个计算两数之和的函数: f…

js实现搜索

js实现搜索

实现搜索功能的方法 在JavaScript中实现搜索功能可以通过多种方式完成,以下是几种常见的实现方法。 使用数组的filter方法 通过数组的filter方法可以筛选出符合条件的数据项。假设有一个…

js 实现跳转

js 实现跳转

使用 window.location.href 进行跳转 通过修改 window.location.href 可以跳转到指定 URL,浏览器会加载新页面: window.location.hre…

js实现排序

js实现排序

数组排序方法 JavaScript提供了内置的sort()方法用于数组排序。默认情况下,sort()将元素转换为字符串并按照Unicode码点排序。对于数字排序,需传入比较函数。 const num…