getElementsByClass
The DOM provides a number of powerful methods for accessing nodes in a document. But there are also some surprising omissions.
For instance, although we have an insertBefore
method, there is no corresponding insertAfter
. Still, it’s possible to recombine existing DOM methods to plug the gaps in the DOM specs.
One of the most useful DOM methods of all is getElementById
. It would be equally useful to have a getElementsByClass
method.
Many, many coders have stepped up to bat on this issue by recombining getElementsByTagName("*")
and className
. The tricky bit is matching the value of className
with the class you’re looking for. Remember that classes can be combined by separating them with spaces.
I came across a nice getElementsByClass
function from Dustin Diaz:
function getElementsByClass(node,searchClass,tag) {
var classElements = new Array();
var els = node.getElementsByTagName(tag);
var elsLen = els.length;
var pattern = new RegExp("\b"+searchClass+"\b");
for (i = 0, j = 0; i < elsLen; i++) {
if ( pattern.test(els[i].className) ) {
classElements[j] = els[i];
j++;
}
}
return classElements;
}
It uses a regular expression to match the className
which is perhaps a bit more resource-intensive than just using something like indexOf
but it decreases the chances of getting false positives.
The function takes three arguments: node
, searchClass
and tag
.
The node
can simply be document
if you want to search the whole document or you can pass it a result from getElementById
(for example).
The searchClass
parameter is the name of the class you want to match.
The tag
parameter allows you to restrict the search to a specific tag. You can simply use the wildcard (“*”) to search all tags.
All in all, a nice little function.
出处:http://sirkevin.cnblogs.com
GitHub:https://github.com/backslash112
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
posted on 2011-08-29 09:49 backslash112 阅读(571) 评论(1) 编辑 收藏 举报