How to sort an array of javascript objects using element.name

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

What I want to do is iterate over all the elements of the form and check 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 my code that works fine if I comment on 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 elements have no names. Does anyone have another easier way to sort an array of DOM elements through their .name?

+3
source share
3 answers

:

$$('#myForm *[name]').sortBy(function(el){ return el.name; });
+3

, sort() DomElementList, .elements.

, Array.sort DomElementList Javascript.

DOM, , .

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]);
}
+1

An implementation without if , based on the built-in js sort function .

elements.sort(function(a, b) { return 2 * (a.name > b.name) - 1; })
+1
source

Source: https://habr.com/ru/post/1625890/


All Articles