David G
David G

Reputation: 96790

Why doesn't this getElementById function work?

<div id="t">gf</div>
<div id="g">ds</div>

function $() {
    return document.getElementById(arguments);
}

$('t', 'g').style.color = "red";

Is there something that I did wrong. It says cannot call style of null...

Upvotes: 1

Views: 1711

Answers (2)

Joel Martinez
Joel Martinez

Reputation: 47751

function $(a, f) {
    a.forEach(function(id) {
        f(document.getElementById(id));
    });
}
$(['t', 'g'], function(d) {
    d.style.color = "red";
});

Upvotes: 1

Cristian Sanchez
Cristian Sanchez

Reputation: 32097

function $() {
    return document.getElementById.apply(document, arguments);
}

You need to use the apply method to call a function using an an array as the arguments. The apply function also needs the context, so you need to pass document as well.

Also, getElementById only accepts a single argument and returns a single element (AFAIK), so this is basically useless. Not to mention even if it did accept multiple arguments to return multiple elements, you still wouldn't be able to use the resulting array in that manner.

Upvotes: 4

Related Questions