/    Sign up×
Community /Pin to ProfileBookmark

Adding, Removing DOM nodes in their Alpha Sorted Order (by ID)?

I’m attempting to add and remove elements in sorted order. but the logic is getting complex and I’d like to keep it as simple as possible.

Would it be possible to traverse all the children (next level) of a DOM node so I can determine where it should be placed?

to post a comment
JavaScript

2 Comments(s)

Copy linkTweet thisAlerts:
@ZeroKilledMar 01.2009 — some time ago i wanted to achieve something similar: sort in alphanumerical the child of a node within a given element, but suddenly I give up. what follow is the code i came up today. i don't like the code, but anyway, maybe you can grasp some idea:
[code=html]
<div id='tosort'>
<p>one phrase</p>
<p>the next phrase</p>
<p>z last because begin with z</p>
<p>and first</p>
<div>contain string'</div>
</div>

<script type='text/javascript'>
onload = function(){
var nodes = [];
var text = [];
var elem = document.getElementById('tosort');

for(var i = 0; i < elem.childNodes.length; i++)if(elem.childNodes[i].nodeType == 1)nodes.push(elem.childNodes[i]);
for(var i = 0; i < nodes.length; i++)text.push(nodes[i].firstChild.nodeValue);
text.sort();
while(text.length){
for(var j = 0; j < nodes.length; j++)if(text[0] == nodes[j].firstChild.nodeValue)elem.appendChild(nodes[j]);
text.shift();
}
}
</script>
[/code]


[B][SIZE="3"]about the code[/SIZE][/B]

the code operate correctly if each child only contain text. that is, if the firrst child of each nodes is an element, then the code can't grab the text. guess this is the main reason i don't like the code.
Copy linkTweet thisAlerts:
@cluettrauthorMar 03.2009 — Thanks, what I did was keep multiple arrays and then processed a function against those arrays to determine where new items should be inserted. It works for the most part although I'm having an issue with the splice array method. I'm going to post about that shortly. Very odd behavior.
×

Success!

Help @cluettr spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.16,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...