Reputation: 143
There are some tags and I need to sort them to display in alphabetical order by id using JavaScript(without jQuery).
<div id="tags">
<p id="b"></p>
<p id="a"></p>
<p id="d"></p>
<p id="c"></p>
</div>
Here is how it must look:
<div id="tags">
<p id="a"></p>
<p id="b"></p>
<p id="c"></p>
<p id="d"></p>
</div>
I tried using sort() method to sort ids and then rearranged them by insertBefore() inside for loop. But it doesn't work. Any ideas?
Upvotes: 0
Views: 333
Reputation: 68393
You can recreate the HTML after sorting
var ps = document.querySelectorAll( "#tags p" );
var sortedPs = Array.from( ps ).sort( (a, b) => a.id.localeCompare( b.id ) ); //sort the ps
document.querySelector( "#tags" ).innerHTML = sortedPs.map( s => s.outerHTML ).join(""); //recreate the markup
<div id="tags">
<p id="b">b</p>
<p id="a">a</p>
<p id="d">d</p>
<p id="c">c</p>
</div>
Note
appendChild
instead of innerHTML
To retain events after soring
var ps = document.querySelectorAll( "#tags p" );
var sortedPs = Array.from( ps ).sort( (a, b) => a.id.localeCompare( b.id ) ); //sort the ps
var tags = document.querySelector( "#tags" );
//create a duplicate hollow tags
var dupTags = tags.cloneNode(false);
sortedPs.forEach( s => dupTags.appendChild ( s ) );
//replace old with new tags
tags.parentNode.replaceChild(dupTags ,tags);
<div id="tags">
<p id="b">b</p>
<p id="a">a</p>
<p id="d">d</p>
<p id="c">c</p>
</div>
Upvotes: 3
Reputation: 2167
I like @gurvinder372 answer more but this is another way to go about it.
function element_sort(id)
{
var e = document.getElementById(id);
var f = document.createDocumentFragment();
var ids = [];
var i = 0;
var l = e.getElementsByTagName('p').length;
while (i < l)
{
ids.push(e.getElementsByTagName('p')[0].id);
f.appendChild(e.getElementsByTagName('p')[0]);
i++
}
ids.sort();
for (var i = 0; i <= ids.length; i++)
{
for (var j = 0; j < f.childNodes.length; j++)
{
if (f.childNodes[j].id==ids[i]) {
e.appendChild(f.childNodes[j]);
}
}
}
}
element_sort("tags")
<div id="tags">
<p id="b">b</p>
<p id="a">a</p>
<p id="d">d</p>
<p id="c">c</p>
</div>
Upvotes: 0