简体   繁体   English

javascript:getElementsByClass

[英]javascript: getElementsByClass

Im looking to do something simple and the site is not heavy with js so im not using a js framework for this. 我希望做一些简单的事情,而该站点使用js并不繁琐,所以我没有为此使用js框架。

I am trying to add event click listener, I am trying to get element by class. 我试图添加事件单击侦听器,我试图按类获取元素。 I found the following function + others that I have tried but for some reason none of them are finding the elements. 我找到了以下我尝试过的函数以及其他函数,但由于某种原因,它们都找不到元素。

function getElementsByClass( searchClass, domNode, tagName) { 
    if (domNode == null) domNode = document;
    if (tagName == null) tagName = '*';
    var el = new Array();
    var tags = domNode.getElementsByTagName(tagName);
    var tcl = " "+searchClass+" ";
    for(i=0,j=0; i<tags.length; i++) { 
        var test = " " + tags[i].className + " ";
        if (test.indexOf(tcl) != -1) 
            el[j++] = tags[i];
    } 
    return el;
}
var els = getElementsByClass("wow");
alert(els.length);

i have a couple of divs with the class wow, testing but I keep getting 0. 我的班级有几个div,测试,但我一直保持0。

Assuming your function works properly, do it when the DOM is ready or on window load. 假设您的功能正常运行,请在DOM准备就绪或窗口加载时执行此操作。 Or call it before the end body tag. 或在结束正文标签之前调用它。

DEMO : http://jsfiddle.net/rXApk/ 演示http : //jsfiddle.net/rXApk/

The class attribute takes a space separated list of class names, not a comma separated list. class属性采用空格分隔的类名列表,而不是逗号分隔的列表。

Your test won't match wow, as it looks for wow . 您的测试不符合wow,因为它看起来很wow

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM