javascript - elem is undefined? - Stack Overflow

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

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744395184a4572104.html

相关推荐

  • javascript - elem is undefined? - Stack Overflow

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

    7天前
    30

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信