Bobby Tables
Bobby Tables

Reputation: 1184

elem is undefined?

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?

Upvotes: 1

Views: 5283

Answers (2)

The Alpha
The Alpha

Reputation: 146201

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.

Upvotes: 3

Joseph
Joseph

Reputation: 119847

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.

Upvotes: 4

Related Questions