Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
</head>
<body>
  <div id="x">
    <ul>
        <li>Apple
        <li>Banana
        <li>Blackberry
        <li>Blueberry
        <li>Cherry
        <li>Cranberry
    </ul>
          <ul id="new"></ul>
</div>
</body>
</html>
 
var list = document.querySelector('#x ul'),
    newUl = document.getElementById('new'),
    fruits = [],
    key = "A";
for(var i=0; i<list.children.length; i++){
  fruits.push(list.children[i].innerText);
}
fruits.sort();
for(var i=0; i<fruits.length; i++){
  if(key == fruits[i].split('')[0]){
    var span = document.createElement('span'),
        li = document.createElement('li');
    span.setAttribute('id', key);
    li.innerText = fruits[i];
    if(document.getElementById(key)){
      document.getElementById(key).appendChild(li);
    }
    else{
      span.appendChild(li);
      newUl.appendChild(span);
    }
    
  }
  if(fruits[i+1]){
    key = fruits[i+1].split('')[0];
  }
}
Output

You can jump to the latest bin by adding /latest to your URL

Dismiss x
public
Bin info
anonymouspro
0viewers