Best way to find DOM elements with css selectors(使用 CSS 选择器查找 DOM 元素的最佳方法)
问题描述
在不使用库的情况下,使用 css 选择器查找 Dom 元素的最简单方法是什么?
What's the easiest way to find Dom elements with a css selector, without using a library?
function select( selector ) {
return [ /* some magic here please :) */ ]
};
select('body')[0] // body;
select('.foo' ) // [div,td,div,a]
select('a[rel=ajax]') // [a,a,a,a]
这个问题纯属学术性的.我有兴趣了解这是如何实现的以及障碍"是什么.这个函数的预期行为是什么?(返回数组,或返回第一个 Dom 元素等).
This question is purely academical. I'm interested in learning how this is implemented and what the 'snags' are. What would the expected behavior of this function be? ( return array, or return first Dom element, etc ).
推荐答案
如今,在没有库的情况下做这种事情是疯狂的.但是,我假设您想了解这些东西是如何工作的.我建议您查看 jQuery 或其他 javascript 库之一的源代码.
These days, doing this kind of stuff without a library is madness. However, I assume you want to learn how this stuff works. I would suggest you look into the source of jQuery or one of the other javascript libraries.
考虑到这一点,选择器函数必须包含大量 if/else/else if 或 switch case 语句,以便处理所有不同的选择器.示例:
With that in mind, the selector function has to include a lot of if/else/else if or switch case statements in order to handle all the different selectors. Example:
function select( selector ) {
if(selector.indexOf('.') > 0) //this might be a css class
return document.getElementsByClassName(selector);
else if(selector.indexOf('#') > 0) // this might be an id
return document.getElementById(selector);
else //this might be a tag name
return document.getElementsByTagName(selector);
//this is not taking all the different cases into account, but you get the idea.
};
这篇关于使用 CSS 选择器查找 DOM 元素的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 CSS 选择器查找 DOM 元素的最佳方法
基础教程推荐
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
