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.

 

link:http://domscripting.com/blog/display/18

posted on   backslash112  阅读(578)  评论(1编辑  收藏  举报

编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架

导航

点击右上角即可分享
微信分享提示