I'm attempting to sort a class of divs inside of a div container called #searchResultsWrapper
. I know that the elements I'm referring to in my sort function are correct and are integers. I'm just unsure why it won't work.
var sortedResults = $('#searchResultsWrapper').children().sort(function(a,b){
if(a.getElementsByClassName('searchResultKeywordCount')[0].innerHTML < b.getElementsByClassName('searchResultKeywordCount')[0].innerHTML)
{
return 0;
}
else
{
return 1;
}
});
$('#searchResultsWrapper').empty();
$('#searchResultsWrapper').append(sortedResults);
My HTML is as follows:
<div id="searchResultsWrapper">
<div >
<div >
<div ></div>
</div>
<h1 >some doc heading</h1>
<div >
<div >
some text
</div>
<div >
5
</div>
</div>
</div>
<div >
<div >
<div ></div>
</div>
<h1 >some doc heading</h1>
<div >
<div >
some text
</div>
<div >
3
</div>
</div>
</div>
</div>
I was expecting the list of divs to be rearranged based on a hidden div I have in a .searchResult
child class called .searchResultKeywordCount
.
CodePudding user response:
Things you need to take care of:
.innerHTML
will return you a string, so you will need to convert it to number. You can useNumber()
for that.innerHTML
can have white space which can give unwanted issues. You will have to trim it before conversion.
When you are manipulating DOM elements in loop, its better to look into DocumentFragment. This is an optimisation technique as mutation of DOM element will trigger repaint and reflow
const parent = document.getElementById('searchResultsWrapper')
const allDivs = parent.querySelectorAll('.searchResultWrapper')
const fragment = new DocumentFragment()
const getInnerValue = (div) => Number(
div.querySelector('.searchResultKeywordCount').innerText.trim()
)
Array
.from(allDivs)
.sort((a, b) => getInnerValue(a) - getInnerValue(b))
.forEach((elm) => fragment.append(elm))
parent.innerHTML = ''
parent.append(fragment)
<div id="searchResultsWrapper">
<div >
<div >
<div ></div>
</div>
<h1 >some doc heading</h1>
<div >
<div >
some text
</div>
<div >
5
</div>
</div>
</div>
<div >
<div >
<div ></div>
</div>
<h1 >some doc heading</h1>
<div >
<div >
some text
</div>
<div >
3
</div>
</div>
</div>
</div>