JSFiddle - React, Tailwind, and code Playground
HTML
<div id="selection"></div>
<div>
<label>A: <input id="a" type="checkbox" /></label><br/>
<div>
<label>B: <input id="b" type="checkbox" /></label><br/>
<label>C: <input id="c" type="checkbox" /></label><br/>
</div>
<label>D: <input id="d" type="checkbox" /></label><br/>
<label>E: <input id="e" type="checkbox" /></label><br/>
<div>
<label>F: <input id="f" type="checkbox" /></label><br/>
<label>G: <input id="g" type="checkbox" /></label><br/>
<div>
<label>H: <input id="h" type="checkbox" /></label><br/>
<label>I: <input id="i" type="checkbox" /></label><br/>
</div>
</div>
<label>J: <input id="j" type="checkbox" /></label><br/>
</div>
CSS
#selection {
padding:4px;
border:solid 2px red;
color:red;
margin-bottom:10px;
}
div div
{
margin-left:15px;
}
div
{
border:dotted 1px gray;
padding:10px;
}
body
{
font-size:12px;
font-family:arial;
line-height:2em;
}
JavaScript
$.fn.sortByDepth = function() {
var ar = [];
var result = $([]);
$(this).each(function() {
ar.push({length: $(this).parents().length, elmt: $(this)});
});
ar.sort(function(a,b) {
return b.length - a.length;
});
alert(ar.length);
for (var i=0; i<ar.length; i++) {
result.add($(ar[i].elmt));
};
alert(result.length);
return result;
};
var x = '';
$('input').sortByDepth().each(function(){
x += ($(this).attr("id")) + ' - ';
});
$('#selection').text(x);
//desired:
//I, H, G, F, C, B, J, E, D, A
//H, I, B, C, F, G, A, D, E, J