jquery or javascript to sort attributes of a html object before regex -
as follow on previous question using jquery find .each on .attr() regex,
i sort attributes alphabetically before running them through .each(). final output add child divs in order of attributes.
<div id="myelement" extra1="a" stuff="z" extra9="c" more="y" extra5="b" /div>
when parse through code below, outputs values b,c,a
, need sort elements first order extra1, extra5, extra9, more, stuff
run through .each()+regex values come out a,b,c
var el = $('#myelement'); var attributes = el[0].attributes; $.each(attributes,function(i,attr){ var name = attr.nodename; var val = attr.nodevalue; var regex = /^extra\d$/; if(name.match(regex)) { $(parentdiv).append("<div id="+val+" /div>"); } });â
thx in advance art
per this mdn doc, attributes collection map, not array not have defined order. if wanted sorted, first have put in array, sort , .each()
on sorted array.
or, collect results in .each()
array, sort results , append sorted results in desired order @ end. looking @ code, think less work this:
var el = $('#myelement'); var attributes = el[0].attributes; var output = []; $.each(attributes,function(i,attr){ var name = attr.nodename; var val = attr.nodevalue; var regex = /^extra\d$/; if(name.match(regex)) { output.push("<div id="+val+" /div>"); } });â $(parentdiv).append(output.sort().join(""));
this simple sort works if attributes can sorted lexigraphic order , don't go beyond extra9
. if goes beyond single digit number, you'll have convert digits numbers , use custom sort function generate right sort order this:
var el = $('#myelement'); var attributes = el[0].attributes; var output = []; var regex = /^extra(\d+)$/; $.each(attributes,function(i,attr){ var name = attr.nodename; var val = attr.nodevalue; var matches, item; if(matches = name.match(regex)) { item = {}; item.html = "<div id="+val+" /div>"; item.num = parseint(matches[1], 10); output.push(item); } });â // sort array of objects custom sort function output.sort(function(a, b) { return(a.num - b.num); }); // append data in correct order items sorted (var = 0; < output.length; i++) { $(parentdiv).append(output[i].html); }
Comments
Post a Comment