Home > javascript > Sorting numeric LI tags without omitting the attributes

Sorting numeric LI tags without omitting the attributes

August 28Hits:1
Advertisement

I used the following Javascript to sort an unnumbered list of numeric li-tags as follows:

// 1. get the <UL>-element from the BODY var nList = document.getElementById("allItems"); // 2. extract all the <LI>-elements from that <UL> and put it in a NodeList var nEntry = nList.getElementsByTagName('li');  // 3. we can't sort a NodeList, so first make it an Array var nEntryArray = Array.prototype.slice.call(nEntry, 0);  // 4. sort the array, the normal sort()-function won't do because it is an alphabetical sort // to sort() numeric values, see http://www.w3schools.com/jsref/jsref_sort.asp example, as "Default sort order is alphabetic and ascending. When numbers are sorted alphabetically, "40" comes before "5".  To perform a numeric sort, you must pass a function as an argument when calling the sort method." // the numeric value of the <LI> nodes can be located in nEntryArray[i].firstChild.nodeValue , so compare those  nEntryArray.sort(function(a,b){   return a.firstChild.nodeValue - b.firstChild.nodeValue })  // 5. empty the nList and refill it with those in the correct order at the nEntryArray while (nList.lastChild) {   nList.removeChild(nList.lastChild); }  for (i=0; i<nEntryArray.length; i++) {   nList.appendChild(nEntryArray[i]); } 

If a HTML-code is given with a list as such:

<ul id='allItems'>     <li class="black">100</li>      <li id="note10">10</li>      <li>1</li>      <li>20</li>      <li class="order2">16</li>  </ul>  

it will order the list numerically without omitting the attributes of the <LI>-tags.

It is one of my first JavaScript-attempts, and I was wondering if this is indeed correct or whether it could be simplified. Especially the conversion from Nodelist to Array seems redundant to me, but I haven't found a more gracious solution.

I post this code-block as I was looking on StackOverflow and through Google for a piece of code to help me solve this particular problem, but I couldn't find something that was understandable to a beginner like me. I easily found ways to sort lists , but then the attributes would be omitted and in the end it took me two days (yep, beginner :-)) to come up with this solution.

Any comments?

Answers

There are a few clear improvements I can see when you are reinserting the nodes back into the DOM tree.

for (i=0; i<nEntryArray.length; i++)
{
  nList.appendChild(nEntryArray[i]);
}

1) You may benefit from using a documentFragment to build up your elements then submit them all at once to the nList

2) (micro), cache the length of your array in the for loop.

var df = document.createDocumentFragment();
for( var i = 0, l = nEntryArray.length; i < l; i++) {
    df.appendChild(nEntryArray[i]);
}
nList.appendChild(df);

Otherwise I do not see any issues with this code. http://jsfiddle.net/rlemon/faY3Z/

Related Articles

  • Sorting numeric LI tags without omitting the attributesAugust 28

    I used the following Javascript to sort an unnumbered list of numeric li-tags as follows: // 1. get the <UL>-element from the BODY var nList = document.getElementById("allItems"); // 2. extract all the <LI>-elements from that <UL&

  • Sort Numerically in OO Calc functions alphabetically

    Sort Numerically in OO Calc functions alphabeticallyJanuary 10

    Using Open Office 3.3.0 Calc will sort a list of numbers not in numerical fashion, as would seem reasonable, logical, and rational, but in alphabetical order. Eg: Calc thinks that 103,1000,etc come between 1 and 2. If I change the format to of the ce

  • List files sorted numericallyMarch 9

    I have a bunch of files from log1 to log164. I'm trying to LIST the directory (sorted) in a UNIX terminal but the sort functions are only providing the format like this: home:logs Home$ ls -1 | sort log1.gz log10.gz log100.gz log101.gz log102.gz log1

  • How to list file names in a directory sorted numeric in a command prompt window?January 28

    I need to dir my files in a folder, but the sorter is not same as displayed in Windows Explorer. For example if I've files with 112 and 0113 as file names in the folder, dir in console window list them in order 0113 and 112. How to list file names in

  • Is it ok to create a form tag without an action attribute that contains several input elements without namesFebruary 13

    Is it ok to create a form tag without an action attribute that contains several input elements without names? I just want to use this form to validate <input type="number"> controls' content. --------------Solutions------------- Yes, it's

  • How to create a constant numeration of ID (indexing) in an attribute table (ArcMap)November 13

    Is it possible to create a constant indexing (as a numbers) in an attribute table of the theme with many objects that manner that it will remain (will not change) during update of this theme? I found the instrument "Drop Index (Coverage)", but i

  • Excel Sort Numeric Column By NumberOctober 4

    I have a column of integers in my spreadsheet, and the column is formatted as a number. Each cell inside the column is formatted as a number. But I can't seem to sort them in numerical order - you know, 1,2...9,10,11... Instead, it always sorts them

  • Add HTML link tag with dynamic SRC attribute to masterpage HEAD sectionFebruary 10

    I need to add a <link> tag with a dynamic src attribute to a custom masterpage <head> section pointing to a current SPWeb library like this: <link rel="alternate" type="application/rss+xml" title="RSS Comments"

  • Sorting numerically in a comma-delimited file with UnixAugust 27

    I've got a comma-separated file that looks like this: 100,00869184 6492,8361 1234,31 200,04071 I want to use sort to sort this file numerically by the first column only. Desired Result: 100,00869184 200,04071 1234,31 6492,8361 How do I achieve this u

  • How can I sort, filter and tag files/images in Android ICS 4.0?October 17

    A little background Im a bit into graphic design, digital painting etc, and I like to draw on the run, away from my desktop. For drawing, I often need reference materials - some pictures of things I would like to draw. While drawing/designing a futur

  • Any way to get Wyvern or Wygwam to set a tag PLUS its required attributes?March 28

    I know how to set up custom styles in Wyvern and Wygwam so that my client can apply, say, a <dfn> tag or <abbr> tag to some text. And I can set attributes within that tag. But the values of the attributes (in this case, lang and title attribut

  • GeoServer with FeatureGrid alpha sorts numeric fieldsJuly 10

    I'm new to GeoServer so if I miss any information please let me know. We're running GeoServer v2.2 with FeatureGrid. When a query is run it returns all the rows correctly, but when we try to sort what should be numeric fields by clicking in the colum

  • What is the SEO impact of using an anchor tag without a href attribute?December 15

    For better user experience, all top level items in the primary menu are set to an empty href so that they only serve as labels for navigation menu sections. They cannot be clicked on and lead nowhere not even href="#". Below is an example: Categ

  • How to force sorting of my tag list?December 30

    My list of nested Evernote tags, after some careless tag creation and renaming, is no longer in alphabetical order. I know that if I remove each tag from its parent tag, and the re-add, it will be inserted in an alphabetically consistent location. Bu

  • JavaScript regex: Find a tag and get some attribute valuesJanuary 25

    i need to capture a html tag by class and some attribute value. I've resolved the first part, capturing the tag by class (the querySelector should be something like: 'input.hashtag'): <input type="text" value="#tag3" notified="

  • Numerical POS tag training in nltk (python)January 18

    To create a natural language calculator, I tried TrigramTagger from nltk. I want to tag multiplication and 2 numbers in given sentences. For example: "What is product of 5 and 7", here 'product' is 'binary.multiply', '5' is 'num-1', and '7' is '

  • Anchor tag generates blank href attribute using echo esc_url( )

    Anchor tag generates blank href attribute using echo esc_url( )June 25

    Following is my categories page. It's listing the all categories in the page. But when <a href> gets blank value here. see the attached screen shot. Why href is blank here li><a href="<?php echo esc_url( $category_link ); ?>"&g

  • sort every field numerically, varying field countsMarch 20

    I'm trying to sort some data using sort. I noticed it was sorting by digit rather than number, so I added the -n flag. It then seemingly only numerically sorts on the first field though. Breaking it down by field is a problem as the lines have varyin

  • What does sort -n do with non numeric values? March 20

    I'm trying to sort some data using sort. I noticed it was sorting by digit rather than number, so I added the -n flag. It then seemingly only numerically sorts on the first field though. Breaking it down by field is a problem as the lines have varyin

  • Numerically sorting files May 14

    Possible Duplicate: List files sorted numerically How can I sort this according to the number of last field? I tried with sort -t ' ' -k9,10n: -rw-r--r-- 1 root root 440 May 14 08:52 test.txt.6 -rw-r--r-- 1 root root 470 May 14 08:52 test.txt.8 -rw-r

Copyright (C) 2017 ceus-now.com, All Rights Reserved. webmaster#ceus-now.com 14 q. 0.513 s.