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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值