开发者

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 speci开发者_StackOverflowfic fieldset.

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


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


Using jQuery (yay!):

$('#fieldset-id :input').each(function(index,element) {
    //element is the specific field:
    $(element).doSomething();
});


Note the solution below is for NON-JQUERY Implementations.

Implement a getElementsByClassName Method like this:

After you implement the code below you can then use document.getElementsByClassName("elementsInFieldSetClass") it will return an array of the elements with that class.

function initializeGetElementsByClassName ()
        {
            if (document.getElementsByClassName == undefined) {
                document.getElementsByClassName = function(className)
                {
                    var hasClassName = new RegExp("(?:^|\\s)" + className + "(?:$|\\s)");
                    var allElements = document.getElementsByTagName("*");
                    var results = [];

                    var element;
                    for (var i = 0; (element = allElements[i]) != null; i++) {
                        var elementClass = element.className;
                        if (elementClass && elementClass.indexOf(className) != -1 && hasClassName.test(elementClass))
                            results.push(element);
                    }
                    return results;
                }
            }
        }

window.onload = function () {
    initializeGetElementsByClassName();
};


Another jQuery solution here.

If you are simply adding a class(es) to the elements, it's this simple:

$('fieldset :input').addClass('newClass');

.addClass() (like many other jQuery functions) will work on all of the elements that match the selector.

Example: http://jsfiddle.net/HANSG/8/


Permanently? Find & replace in your editor of choice.

When the user clicks something? jQuery way:

$('fieldset <selector>').each(function() {
  $(this).removeClass('old').addClass('new');
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜