Insert UL items into alphabetical list using jQuery

I have an unordered list that is generated dynamically and is automatically ordered alphabetically. However, I would like the list to contain every letter (A–Z), but for the items which get added with jQuery not to be links.

<ul class="letters-listing">
<li><a href="#">a</a></li>
<li><a href="#">b</a></li>
<li><a href="#">c</a></li>
<li><a href="#">d</a></li>
<li><a href="#">e</a></li>
<li><a href="#">f</a></li>
<li><a href="#">g</a></li>
<li><a href="#">h</a></li>
<li><a href="#">j</a></li>
<li><a href="#">k</a></li>
<li><a href="#">l</a></li>
<li><a href="#">m</a></li>
<li><a href="#">n</a></li>
<li><a href="#">o</a></li>
<li><a href="#">p</a></li>
<li><a href="#">r</a></li>
<li><a href="#">s</a></li>
<li><a href="#">t</a></li>
<li><a href="#">v</a></li>
<li><a href="#">w</a></li>

So, for example, no letter “i” is output as a list item, so I would like to insert <li>i</li> in the relevant place in the list so I have a full A–Z listing.

Would I use an if statement and append for this?

Thanks in advance.

What would be the normal way is to use a for loop that goes from A to Z, and inside that for loop to use an if statement that checks whether that letter already exists in the list. If it doesn’t, then you can add that letter to the list.

Thanks Paul. This is a start:

	$('.letters-listing li').each(function(){
	    if(condition) {
	            // do nothing 
            else {
	            $(this).append('<li>insert letter here</li>');

How is this looking as an overall start? Any idea what the condition would be (i.e. to see if the letter exists)? And then, how would I insert the correct letter if it doesn’t?

Sorry, I’m trying to have a go, but my jQuery is pretty limited.

I’ve got a Codepen here, but it’s not working.

It’s got an array for all the letters, and then I’m doing a search for “a”, and I’m trying to add the item if it doesn’t exist. Then I guess I’d copy the function for each letter in the alphabet.

Any help would be greatly appreciated.

Hi there,

In addition to what Paul has already said, I would use the letter’s char code to create a regular expression and test the <li> element’s content for that.
If it is not present, then the appropriate element can be created and appended.

var charCode,
    i = 0,
    items = $(".letters-listing > li");

for(charCode=65; charCode < 91; charCode++){ 
    var letter = String.fromCharCode(charCode).toLowerCase(),
        anchor = '<a href="#">' + letter + '</a>',
        expression =  RegExp(anchor);

    if(i >= items.length){
        $(".letters-listing").append("<li>" + anchor + "</li>");     
    } else if(!items[i].innerHTML.match(expression)){
        $(items[i]).before("<li>" + anchor + "</li>");
    i ++;

Here’s a fiddle.

If you have any questions about what I’ve done, just let me know.

Oh wow, that’s awesome. Thanks – works perfectly!