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 阅读(578) 评论(1) 编辑 收藏 举报
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架