开发者

Why doesn't this getElementById function work?

开发者 https://www.devze.com 2023-03-10 10:52 出处:网络
<div id=\"t\">gf</div> <div id=\"g\">ds</div> fu开发者_高级运维nction $() {
<div id="t">gf</div>
<div id="g">ds</div>

fu开发者_高级运维nction $() {
    return document.getElementById(arguments);
}

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

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


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号