Martyn Ball
Martyn Ball

Reputation: 4885

JS: GetElementsByName from within form

im trying to get an element by name in my form, but for some reason im getting this error:

Uncaught TypeError: frm.getElementsByName is not a function

Here is my code:

function doc(id) { return document.getElementById(id); }

function switchFields() {
    var e = doc("slcSubmit");
    var sel = e.options[e.selectedIndex].value;
    var frm = doc("frmSendmessage");

    var messageFields = [frm.getElementsByName("name"),frm.getElementsByName("email")]; //List of objects

    //Give each object a new class
    for (var i=0;i<messageFields.length;i++) {
        messageFields[i].class = "test";
    }
}

Upvotes: 3

Views: 2618

Answers (2)

Joshua Dannemann
Joshua Dannemann

Reputation: 2080

If you need a substitute for getElementsByName that does not require Jquery, here is a function that you can use.

    //g is the dom element, cl is the value for the name attribute
        function getElementsByName(g, cl) {
            var e = [], b = g.childNodes, a, b, f, k;
            for (a = 0; a <= b.length - 1; a += 1) {
                if (b[a].getAttribute) {
                    if (cl == b[a].getAttribute("name")) {
                        e.push(b[a])
                    }
                }
                f = getElementsByName(b[a], cl);
                for (k = 0; k <= f - 1; k++) {
                    e.push(f[k])
                }
            }
            return e
        }

Upvotes: 1

blex
blex

Reputation: 25634

getElementsByName is not a function that can be applied to any node (only to document).

I think what you are looking for is frm.querySelector('[name="TheName"]')

Upvotes: 9

Related Questions