Search code examples
jqueryreplaceclosureseachnested-loops

Replacing multiple text strings in blocks of text using jquery.each()


I'm currently trying to create nested loops to apply clickable definitions to words within several blocks of texts. The first, outer loop iterates through the definition names and ids in each class 'n-concept' and creates a new <span> to be used by the inner loop. The inner loop then goes through each block of 'original-text' and replaces each instance of the 'nounName' with the <span> template created in the first loop. Here's the code...

$(document).ready(function(){   
    $('.n-concept').each(function(){        
        var nounName = $(this).find('h3').html();
        var nounID = $(this).attr('id');
        var newString = '<span data-vocabID="'+nounID+'" class="noun-name">'+nounName+'</span>';

        $('.original-text').each(function(){
            var newText = $(this).text().replace(RegExp(nounName, 'gi'), newString);
            $(this).html(newText);                  
        });
    });
});

Currently, the loops are working but only the values for the last iteration of the 'n-concept' loop are being applied, i.e., it's not preserving the changed value of the original text. I'm a bit new to javascript and jquery so forgive me if this is a really simple problem to solve. From reading up, it seems like a closure is what I might need here? Any help would be greatly appreciated :)


Solution

  • You should use html() method instead of text(), because the text() method ignores the spans that you add in the previous iteration.

    http://jsfiddle.net/erztfr5s/