0

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());


})();

4 Answers 4

1

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);


})();
Sign up to request clarification or add additional context in comments.

Comments

0
(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:

Comments

0

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());

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.