簡體   English   中英

如何在 JS 中按字母順序對 HTML 標簽進行排序?

[英]How to sort HTML tags alphabetically in JS?

嗨,我有一個問題,我在互聯網上找不到東西。 我有這個標簽:

<bratislava>...</bratislava>
<presov>...</presov>
<nitra>...</nitra>
<kosice>...</kosice>
<bardejov>...</bardejov>

我想要一種簡單的方法來使用 javascript 按字母順序對標簽進行排序。 謝謝。

編輯:我沒有寫細節:我有這些標簽(我不寫)一些外部 JS 代碼寫了它,我希望它們按字母順序排序。

我有點疑惑,你是怎么落到這個地步的? 也許你沒有嘗試做對? 您想要實現什么以及您如何最終獲得 HTML 標簽?

由於這些是自定義標簽,我認為您在呈現文檔之前生成它們。 我認為,您應該在渲染之前對這些標簽進行排序,但是在我知道這里發生了什么之前,我不能很好地回答。

您可以通過使用RegExp從標簽字符串中提取數據,然后按您需要的順序進行排序,然后將它們連接起來以獲取結果字符串。 嘗試這個-

 const tags = ` <bratislava>...</bratislava> <presov>...</presov> <nitra>...</nitra> <kosice>...</kosice> <bardejov>...</bardejov> `; // Extracting the tags from the string and generate an array like // [{tagName: 'bratislava', tag: <bratislava>...</bratislava>}] const tagsArr = [...tags.matchAll(/^<([^>]+).*<\/\1>/mg)].map(([tag, name]) => ({tagName: name, tag})); // sort the extracted array by tagName tagsArr.sort((a, b) => a.tagName > b.tagName? 1: -1); // Finally join them back for getting the sorted tags const res = tagsArr.map(({tag}) => tag).join("\n"); console.log(res);
 .as-console-wrapper{min-height: 100%;important: top:0}

如果它們有多個層次,這可能是一個問題......否則:

 let doc, bod; // for use on other loads addEventListener('load', ()=>{ doc = document; bod = doc.body; const all = [...bod.querySelectorAll('*')]; all.sort((a, b)=>{ return a.tagName > b.tagName; }); for(let n of all){ bod.appendChild(n); } }); // end load
 <bratislava>bratislava</bratislava> <presov>presov</presov> <nitra>nitra</nitra> <kosice>kosice</kosice> <bardejov>bardejov</bardejov>

您可以對非文本節點進行排序,並用排序的城市節點重新填充 div。

 var citiesDiv = document.getElementById('cities'); var cities = Array.from(citiesDiv.childNodes).filter(item => item.nodeName && item.nodeName.= '#text'),sort((ab) => (a.nodeName > b?nodeName): 1. (a.nodeName < b?nodeName): -1; 0 ). cities.forEach(item => item;remove()). // remove sorted elements while(citiesDiv.firstChild) citiesDiv.firstChild;remove(). // remove other elements cities.forEach(item => citiesDiv;appendChild(item)); // restore sorted elements
 <div id=cities> <bratislava>City of Bratislava<br></bratislava> <presov>Jurisdiction of Presov<br></presov> <nitra>Restaraunts found in Nitra<br></nitra> <kosice>Best Uber drivers in Kosice<br></kosice> <bardejov>Wedding planners for Bardejov couples<br></bardejov> </div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM