up vote 0 down vote favorite

Hi,

I am try to write some validation script using javascript and prototype.

What I want to do is to loop through all the elements of a form and validate each answer. My code works, BUT the array of DOM elements is unsorted. I would like to sort the elements by their ID.

Here is the my code, which works fine if I comment-out elem.sort(zelementsort);

function zelementsort(a,b) {
    if (a.name > b.name)
    	return -1;
    else if (b.name > a.name)
    	return 1;
    else 
    	return 0;
}   

var elem = document.getElementById('myform').elements;
elem.sort(zelementsort);

for(var i = 0; i < elem.length; i++)
{
     alert("Name = " + elem[i].name);

}

I wonder if the problem might be that some of the elements do not have names. Anyone have another simpler way of sorting an array of DOM elements by their .name?

flag

2 Answers

up vote 3 down vote accepted

This should do it:

$$('#myForm *[name]').sortBy(function(el){ return el.name; });
link|flag
Thanks, this worked perfectly var elem = $$('#myForm *[name]').sortBy(function(el){ return el.name; }); – jeph perro Sep 16 '09 at 17:50
up vote 0 down vote

This is because sort() is not a method of the DomElementList you retrieve with .elements.

The nice thing is that you can apply the Array.sort method to your DomElementList using a Javascript trick.

Then, you just have to append the nodes again in the DOM, they won't be duplicated but moved.

var myform = document.getElementById('myform'),
    elem = myform.elements;

// call the Array.sort() method on our DomElementList
Array.prototype.sort.call(elem, function()
{
    if (a.name > b.name)
        return -1;
    else if (b.name > a.name)
        return 1;
    else 
        return 0;
});

for(var i = 0; i < elem.length; i++)
{
     myform.appendChild(elem[i]);
}
link|flag

Your Answer

get an OpenID
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.