Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to loop through all fields in a fieldset?

I would like to change the class for all the fields in a specific fieldset.

Is there a way to loop through the fields in a fieldset?

like image 299
dmr Avatar asked Dec 22 '22 02:12

dmr


1 Answers

You can use getElementsByTagName.

var fieldset= document.getElementById('something');
var fieldtags= ['input', 'textarea', 'select', 'button'];

for (var tagi= fieldtags.length; tagi-->0) {
    var fields= fieldset.getElementsByTagName(fieldtags[tagi]);
    for (var fieldi= fields.length; fieldi-->0;) {

        fields[fieldi].className= 'hello';
    }
}

(If you only care about input fields, you could lose the outer tag loop.)

If you needed them in document order (rather than grouped by tag) you'd have to walk over the elements manually, which will be a pain and a bit slow. You could use fieldset.querySelectorAll('input, textarea, select, button'), but not all browsers support that yet. (In particular, IE6-7 predate it.)

like image 136
bobince Avatar answered Jan 12 '23 05:01

bobince