Matthew
Matthew

Reputation: 2246

Why isn't JavaScript for loop incrementing?

I'm trying to replace the <li> with 1. 2. 3. respectively. I managed to change the <li> to a number, but that number is 0. The loop doesn't want to work. To be honest, this method may be impossible.

Take a look at the Fiddle if you'd like.

This is my function(){...} :

function doIt(){

        var input = document.getElementById("input");
        var li = /<li>/; // match opening li
        var liB = /<\/li>/; // match closing li
        var numberOfItems = input.value.match(li).length; // number of lis that occur


        for(var i = 0; i < numberOfItems; i++) {
            insertNumber(i); // execute insertNumber function w/ parameter of incremented i 
        }

        function insertNumber(number){
            input.value = input.value.replace(li, number + "." + " ").replace(liB, "");
        }


    }

I understand the insertNumber(){...} function is not necessary.

Upvotes: 0

Views: 85

Answers (1)

scrowler
scrowler

Reputation: 24406

Here's an alternative method, turning your HTML textarea contents into DOM elements that jQuery can manipulate and managing them that way:

function doIt() {
    var $domElements = $.parseHTML( $('#input').val().trim() ),
        output = [],
        i = 1;
    $.each($domElements, function(index, element) {
        if($(this).text().trim() != '') {
            output.push( i + '. ' + $(this).text().trim() );
            i++;
        }
    });
    $('#input').val(output.join('\n'));
}

Upvotes: 1

Related Questions