开发者

Trying to change attribute of multiple items in JavaScript, only first item is changing, what am I doing wrong?

<div class="t">Hello</div>
<div class="t">Hello</div>

<script>
    function $$(name) {
        a = document.getElementsByTagName("*");
        for (var i = 开发者_Go百科0; i < a.length; i++) {
            if (a[i].className == name) return a[i];
        }
    }

    $$('t').style.color = "red";
</script>

Only the first div with a class of 't' turned red. What did I do wrong?


You're exiting the loop as soon as a match is found, so by definition only one element will ever get changed.

Oh, and your code will fail if the element you want to match has extra classes on it too.

It would be better to write your code to invoke a callback on all matching elements:

function $$(name, cb) {
    var a = document.getElementsByTagName("*");
    for (var i = 0; i < a.length; i++) {
        if (a[i].className == name) {
            cb.apply(a[i])
        }
    }
}

$$('t', function() {
    this.style.color = 'red';
});

Or, just use a library (e.g. jQuery) that's designed for exactly this sort of job:

$('.t').css('color', 'red');


You loop through all the elements until you find one that matches your condition, then you return it (at which point the loop is exited).

If you want to handle all of them in that fashion, you will need to create an array and push all the matching ones on to it, and then return the array after the for loop have finished. Then you will have to loop over all of them setting the .style.color property in turn.

Alternatively, you could pass a function as an argument to $$ (which is a very unhelpful function name) and call that function on every matching element during the for loop.

Since the question is a generic "What is wrong?" it is probably also worth pointing out that you are using a global a instead of one localised to the function with var, and that many modern browsers have a native getElementsByClassName method which would be much, much faster then your loop over every element.


When function reaches a return ; statement it breakes (and code that called function continues). Thats why you get only 1 element.


You're doing a return in the if()in yourfor()` loop, which means it'll jump out of the function the first time it hits a result, so you'll only ever get the first result.


Your returning when the class is found within the loop. The return statement ends the function and passes back the value, wherever it is called.

You'd be better off adding the element to an array and returning after the loop.

function $$(name) {
        arr = [];
        a = document.getElementsByTagName("*");
        for (var i = 0; i < a.length; i++) {
            if (a[i].className == name) 
            {
                 arr[i] = a[i];
            }
        }
        return arr
    }

    //you'll have to loop over them again here
    $$('t').style.color = "red";

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜