使用css选择器查​​找DOM元素的最佳方法

Ste*_*fan 21 javascript css-selectors

在不使用库的情况下,使用css选择器查​​找Dom元素的最简单方法是什么?

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]
Run Code Online (Sandbox Code Playgroud)

这个问题纯粹是学术性的.我有兴趣了解这是如何实现的以及"障碍"是什么.这个函数的预期行为是什么?(返回数组,或返回第一个Dom元素等).

mie*_*iek 70

除了自定义hacks之外,在最近的浏览器中,您可以使用W3C Selectors API Level 1中定义的本机方法,即document.querySelector()document.querySelectorAll():

var cells = document.querySelectorAll("#score > tbody > tr > td:nth-of-type(2)");
Run Code Online (Sandbox Code Playgroud)

  • +1表示不需要库的简单解决方案. (6认同)
  • 这应该是选定的答案 - 除IE7​​外,所有现代浏览器都受支持吗?2013年8月,这对我来说已经足够了! (4认同)
  • 文档和浏览器支持https://developer.mozilla.org/en-US/docs/Web/API/Document.querySelectorAll (3认同)

Jos*_*lio 3

如今,在没有图书馆的情况下做这种事情是疯狂的。不过,我假设您想了解这些东西是如何工作的。我建议您查看 jQuery 的源代码或其他 javascript 库之一。

考虑到这一点,选择器函数必须包含大量 if/else/else if 或 switch case 语句,以便处理所有不同的选择器。例子:

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.
};
Run Code Online (Sandbox Code Playgroud)

  • 这在现代浏览器中是不必要的。querySelectedAll() 是一个更好的解决方案。 (6认同)
  • 不一定 - 看看 Sizzle(jQuery 的引擎),你不会看到这些。 (2认同)