我想对我的DOM元素进行排序。 这是我的代码
function sortP() {
var p = document.body.getElementsByTagName('p');
Array.from(p)
.sort((a, b) => a.textContent.localeCompare(b.textContent))
.forEach(p => document.body.insertBefore(p, sort))
}
document.getElementById("sort").addEventListener('click', sortP)
<div id="list">
<div><p>foo</p> <span>lorem abc</span></div>
<div><p>baz</p><span>lorem lorem abc</span></div>
<div><p>bar</p><span>lorem lorem loremabc</span></div>
</div>
<button id="sort">sort</button>
结果:
lorem abc
lorem lorem abc
lorem lorem lorem abc
栏
巴兹
foo
但是,我希望它们按照以下方式排序
bar
lorem abc
baz
lorem lorem abc
foo
lorem lorem lorem abc
我不知道如何修正代码以获得正确的结果(我只想对元素p进行排序)
答案 0 :(得分:1)
您在比较和排序上几乎是正确的,但是您应该选择要移动的整个块,即。选择器项应类似于<div><p>foo</p> <span>lorem abc</span></div>
function sortP() {
let blocksList = document.body.querySelectorAll('#list > div');
blocksList = Array.from(blocksList);
blocksList.sort((a, b) => {
return a.querySelector('p')
.textContent.localeCompare(
b.querySelector('p').textContent
);
})
.forEach(p => document.body.insertBefore(p, sort));
}
document.getElementById("sort").addEventListener('click', sortP);
<div id="list">
<div><p>foo</p> <span>lorem abc</span></div>
<div><p>baz</p><span>lorem lorem abc</span></div>
<div><p>bar</p><span>lorem lorem loremabc</span></div>
</div>
<button id="sort">sort</button>
答案 1 :(得分:0)
获取div元素而不是p元素
function sortP() {
var p = document.body.getElementsByTagName('div');
Array.from(p)
.sort((a, b) => a.textContent.localeCompare(b.textContent))
.forEach(p => document.body.insertBefore(p, sort))
}
document.getElementById("sort").addEventListener('click', sortP)
<div id="list">
<div><p>foo</p> <span>abc</span></div>
<div><p>baz</p><span>abc</span></div>
<div><p>bar</p><span>abc</span></div>
</div>
<button id="sort">sort</button>