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";
}
}
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";
}
}
Share
asked Aug 25, 2015 at 20:56
Martyn BallMartyn Ball
4,8959 gold badges63 silver badges145 bronze badges
2 Answers
Reset to default 9getElementsByName
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"]')
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
}