使用 CSS 选择器查找 DOM 元素的最佳方法 [英] Best way to find DOM elements with css selectors

查看:18
本文介绍了使用 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 元素的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆