...

View Full Version : Sorting SPANs by innerText, how?



[Z]
04-18-2005, 07:12 AM
Hi,
how could I sort SPANs by its innerText (IE)?

Page code:

<DIV id=d1>
<SPAN id=sp1>aaa</SPAN><BR>
<SPAN id=sp2>zzz</SPAN><BR>
<SPAN id=sp3>ccc</SPAN><BR>
</DIV>

I want to change d1 innerHTML on body onload event (don't ask me why not before), spans should be sorted:

<DIV id=d1>
<SPAN id=sp1>aaa</SPAN><BR>
<SPAN id=sp2>ccc</SPAN><BR>
<SPAN id=sp3>zzz</SPAN><BR>
</DIV>

TIA

Harry Armadillo
04-18-2005, 07:32 AM
function spanSort(){
var a=[],s=document.getElementsByTagName('span');
for(var i=0;i<s.length;i++)
a[i]=s[i].innerHTML;
a.sort();
for(i=0;i<s.length;i++)
s[i].innerHTML=a[i];
}

[Z]
04-18-2005, 08:00 AM
function spanSort(){
var a=[],s=document.getElementsByTagName('span');
for(var i=0;i<s.length;i++)
a[i]=s[i].innerHTML;
a.sort();
for(i=0;i<s.length;i++)
s[i].innerHTML=a[i];
}

Thanks that did it. You've made my day...

[Z]
04-18-2005, 08:38 AM
']Thanks that did it. You've made my day...
But... I want to sort by innerText only, outer/innerHTML sorting depends on SPANs IDs...

???

<DIV id=d1>
<SPAN id=aaasEjd>www</SPAN><BR>
<SPAN id=a1Dsfsp1>aaa</SPAN><BR>
<SPAN id=zdsEjd>ccc</SPAN><BR>
<SPAN id=bds2s>zzz</SPAN><BR>
</DIV>

Kor
04-18-2005, 11:06 AM
Do you really need id's?

[Z]
04-18-2005, 12:16 PM
Do you really need id's?
Absolutely! That's a specific js-project... I guess I've solved the problem.

function F(){
var a=[],s=document.getElementsByTagName('span');
for(var i=0;i<s.length;i++)a[i]=s[i].outerHTML;
a.sort(C)
for(i=0;i<s.length;i++)s[i].outerHTML=a[i];
}

function C(a,b){
alert(a.replace(/\<s.+?>/i,''))
if(String(a.replace(/\<s.+?>/i,'')) < String(b.replace(/\<s.+?>/i,'')))return -1;
if (String(a.replace(/\<s.+?>/i,'')) > String(b.replace(/\<s.+?>/i,'')))return 1;
return 0;
}

glenngv
04-18-2005, 12:39 PM
Alternative (cross-browser) solution using "2D" array:

function spanSort(){
var a=[],s=document.getElementsByTagName('span');
for(var i=0;i<s.length;i++)
a[i] = [s[i].id, s[i].innerHTML];
a.sort(
function(a,b){
if(a[1] < b[1])
return -1;
if(a[1] > b[1])
return 1;
return 0;
}
);
for(i=0;i<s.length;i++){
s[i].id=a[i][0];
s[i].innerHTML=a[i][1];
}
}
This works cross-browser as it doesn't use the IE-proprietary property outerHTML.

[Z]
04-18-2005, 02:04 PM
Alternative (cross-browser) solution using "2D" array:
This works cross-browser as it doesn't use the IE-proprietary property outerHTML.
Thanks a lot!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum