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

查看:844
本文介绍了用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]

这个问题纯粹是学术的。我有兴趣了解这是如何实现的,什么是'snags'。这个函数的预期行为是什么? (返回数组或返回第一个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天全站免登陆