2017-08-30 67 views
-4

p標籤排序的話,我需要我的<p></p>標籤內排序的話,所以當我這樣做:從HTML收集

var paragraphs = document.getElementsByTagName("p"); 

我得到的HTML集合。

在這一點上,我不知道如何繼續。如何從集合中獲取單個段落並對它們進行排序?

感謝您的幫助。

+1

反對票是b/c,您需要顯示您已嘗試達到這一點,然後發佈一個失敗代碼的小例子。 – flyer

+0

聽起來像作業 –

+0

@ZachM。所以我有一個問題,我不能在這裏問一個問題?難道你沒有什麼更有趣的事情比嘮叨嗎? – grabnem

回答

0

如果您將html嵌套在<p>標記中,這會變得更復雜,但您可以將文本拆分爲字符串數組,然後sort the array

這裏是顯示這個整體提琴:https://jsfiddle.net/tuc2d5f1/9/

這裏是基本的JS代碼。它沒有考慮節點內的html,也沒有複雜的字符替換。

for (var i in paragraphs) { 
    if (!paragraphs.hasOwnProperty(i)) continue; 
    // skip this iteration if it's not an actual element 

    console.log("Starting paragraph: " + i); 
    var text = paragraphs[i].innerHTML.toString().toLowerCase(); 
    // get the text of the node 

    text = text.trim().replace(".", ""); 
    // you need to remove special chars. Regex would be best 

    var txtAry = text.split(" "); // split to an array based on spaces 
    // you should first replace all newline/return chars with spaces 

    txtAry.sort(); // this is an array of strings in alphabetical order 

    console.log(txtAry); 
} 
+0

我得到了那部分,我遇到了forEach循環的問題,獲得了所有單個段落標記innerHTML – grabnem

+0

@grabnem @grabnem用一個工作小提琴看到我的更新答案。 – luxdvie

1

getElementsByTagName返回包含HTML集合的類似數組的對象。您需要循環瀏覽這些項目並從中提取html

var paragraphs = document.getElementsByTagName("p"); 
var html; 
for (var i=0; i<paragraphs.length; i++) { 
    /* cache plain string */ 
    html = paragraphs[i].innerHTML 
    /* convert into an array, sort it as an array, convert back to string */ 
    html = html.split('').sort().join(''); 
    console.log(html); 
} 
+0

我試過了,它似乎沒有工作,它根本沒有進入循環,沒有日誌,感謝您的答案,雖然 – grabnem

+0

請按照此示例:[解決方案](http:// jsbin。 com/tosucohaqe/edit?html,js,console,output) - 那是你在找什麼? – Melcma

+0

它很接近,下面的答案更多的是我在找的東西,但是謝謝你的回答! – grabnem