题解 | #列表内容排序再渲染#
列表内容排序再渲染
https://www.nowcoder.com/practice/2dffcb354a484995894655a5547b0b49
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <ul id="myList"> <li id="item1">项目 1</li> <li id="item3">项目 3</li> <li id="item2">项目 2</li> <li id="item4">项目 4</li> </ul> <script> function sortAndReturnTextContent() { const items = document.getElementById('myList').children; // 在此补全代码 const itemsArray = Array.from(items).sort((a,b)=>a.id>b.id?1:-1) const myList = document.getElementById('myList') myList.innerHTML = itemsArray.map(item=>item.outerHTML).join('') } sortAndReturnTextContent() </script> </body> </html>