最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - elem is undefined? - Stack Overflow

programmeradmin7浏览0评论

When I run the following piece of code, the firebug console says that elem is undefined, although...it isn't!

var domTools = {};
domTools.searchInElements = function (elem, pattern) {
    if (pattern.constructor !== RegExp) {
        throw "Pattern must be a RegExp";
    }
    if (elem.constructor !== String) {
        throw "Element must be a String";
    }
    elem = document.getElementsByTagName[elem];
    var matches = [];
    for (e = 0; e < elem.length; e++) {
        if (pattern.test(elem[e].innerHTML)) {
            matches.push(elem[e]);
        }
    }
    return matches;
}
domTools.searchInElements("p", /hello/);

It gives me the error during the for statement. All this code is being run whle the page is already loaded. Why is this happening?

When I run the following piece of code, the firebug console says that elem is undefined, although...it isn't!

var domTools = {};
domTools.searchInElements = function (elem, pattern) {
    if (pattern.constructor !== RegExp) {
        throw "Pattern must be a RegExp";
    }
    if (elem.constructor !== String) {
        throw "Element must be a String";
    }
    elem = document.getElementsByTagName[elem];
    var matches = [];
    for (e = 0; e < elem.length; e++) {
        if (pattern.test(elem[e].innerHTML)) {
            matches.push(elem[e]);
        }
    }
    return matches;
}
domTools.searchInElements("p", /hello/);

It gives me the error during the for statement. All this code is being run whle the page is already loaded. Why is this happening?

Share Improve this question asked Jun 17, 2012 at 0:04 Bobby TablesBobby Tables 1,1844 gold badges15 silver badges25 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

It's () and not []

elem = document.getElementsByTagName(elem);

Think of getElementsByTagnName() as a function call so you won't forget that it uses (). And don't forget using the developer console F12 to spot these problems.

As Joseph the Dreamer already found the bug that was causing the error because you've used document.getElementsByTagName[elem]instead ofdocument.getElementsByTagName(elem).

But you may face another problem with this call domTools.searchInElements("p", /hello/); because it'll match hello, helloo, hellos etc so you should use

domTools.searchInElements("p", /^hello$/)

OR just another idea here.

发布评论

评论列表(0)

  1. 暂无评论