2

I am VERY new to JavaScript. I have looked at several previously answered questions along this line. My HTML is roughly:

<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.skills{
list-style:none;
padding: 0;
margin-bottom: 200px;
}
.skills li{
width: 200px;
float: left;
padding: 0;
 }
 </style>
 </head>
  <body>
  <h2>Skills</h2>
<ul class="skills">
    <li>a</li>
    <li>b</li>
    <li>c</li>
    <li>d</li>
    <li>e</li>
</ul>
  </body>
  </html>

I have tried to use:

 <script type="text/javascript">
   function sortLi()
    {
      var skills = [getElementsbyTagName("li")];
      skills.sort();
          var x=document.getElementsByTagName("li");
              x.innerHTML=skills;
     }
  </script>

and by swapping .getElementsbyTagName with .getElementsbyClass("skills") to no avail. I know that I am doing something wrong but just can't put my finger on it.

Zandorph
  • 21
  • 1
  • I guess I should have said I am looking to alphabetically sort. – Zandorph Nov 12 '12 at 20:58
  • you should use `getElementById('skills')` to get the element and of course set the `ul` element to have the id of skills – kingkode Nov 12 '12 at 21:02
  • var x=document.getElementsByTagName("ul")[0]; – mplungjan Nov 12 '12 at 21:06
  • Probably this answer can be of help to you: http://stackoverflow.com/a/1135099/189431 . Demo here: http://jsfiddle.net/stodolaj/De8Ku/ – Koen. Nov 12 '12 at 21:07
  • ok I made your corrections McMastermind and also corrected my typos (formatting) and still have no luck :( – Zandorph Nov 12 '12 at 21:09
  • Koen, I did see that one. I just do not want it with a button, on load is perfect for my needs. I know that I am all around this thing but I cannot land the answer. – Zandorph Nov 12 '12 at 21:12
  • Anything called getElements in plural returns a collection and needs [0] to get at the first item. Also add `document.` to your getElements... – mplungjan Nov 12 '12 at 21:13

1 Answers1

1

Check out this solution (here is a link at jsfiddle.)

var mylist = $('.skills');
var listitems = mylist.children('li').get();
listitems.sort(function(a, b) {
    return $(a).text().toUpperCase().localeCompare($(b).text().toUpperCase());
})
$.each(listitems, function(idx, itm) {
    mylist.append(itm);
});​

This uses jQuery and is almost wholly lifted from another Stackoverflow answer.

Basically you have some syntax errors, you don't call your code, etc. Take a look at how the working solution I've linked to at jsfiddle functions and see if that helps.

Community
  • 1
  • 1
rg88
  • 20,742
  • 18
  • 76
  • 110