Stereo99
Stereo99

Reputation: 232

Adding a class to an array of elements with forEach not working?

I converted a node list returned by the querySelector() method to an array but I still can't get forEach to work (I just want to add a class). Can someone tell me what I'm doing wrong?

My code is extremely simple as I'm very new to JS.

This is the HTML:

<table>
    <tr>
        <th>This is a th</th>
        <th>This is a th</th>
        <th>Target</th>
        <th style="display: none;"></th>
    </tr>
    <tr>
        <td>This is a table cell</td>
        <td>This is a table cell</td>
        <td>Target</td>
        <td style="display: none;"></td>
    </tr>
</table>

JS:

(function(){

    "use strict";

    var th = Array.prototype.slice.call(document.querySelectorAll("th")),
        td = Array.prototype.slice.call(document.querySelectorAll("td"));

    function test(index, el, array) {
        el.className = "color";
    }

    th.forEach(test());


})();

Upvotes: 0

Views: 75

Answers (4)

anurupr
anurupr

Reputation: 2344

Your argument order was wrong . This should work

(function(){

    "use strict";

    var th = Array.prototype.slice.call(document.querySelectorAll("th")),
        td = Array.prototype.slice.call(document.querySelectorAll("td"));

    function test(el, index, array) {
        el.className = "color";
    }

    th.forEach(test);


})();

Upvotes: 1

krishnan
krishnan

Reputation: 3

Here is a working fiddle http://jsfiddle.net/7pVD6/

(function(){

    "use strict";

    var th = Array.prototype.slice.call(document.querySelectorAll("th")),
        td = Array.prototype.slice.call(document.querySelectorAll("td"));

    function test(el) {
        el.className = "color";
    }

    th.forEach(function(el)
               {
                   test(el)
               });


})();

You should pass a callback that takes a single argument(the element) in the forEach or directly pass test(el)

Upvotes: 0

Mehran Hatami
Mehran Hatami

Reputation: 12961

Firstly you already have th in forEach, so you don't need to pass it again.

then you should do it like:

th.forEach(test);

or change the test function:

function test() {
    return function(index, el, array){
        el.className = "color";
    };
}
th.forEach(test());

Upvotes: 0

Vicky Gonsalves
Vicky Gonsalves

Reputation: 11717

(function(){
        "use strict";
        var th = Array.prototype.slice.call(document.querySelectorAll("th")),
                td = Array.prototype.slice.call(document.querySelectorAll("td"));

        function test(el) {
            el.className = "color";
        }
        th.forEach(function(el){
            test(el);
        });
    })();

Try This:

Upvotes: 0

Related Questions