0

I have some JQuery that takes 2 strings of HTML. Each string contains exactly the same html except in one string the innertext contents of each element will be different, this string is called newContent, the other oldContent.

My function: iterates over oldContent, for each element of the class "updatable"(inside oldContent) we change its innerText to the innerText of the same element in newContent.

My Problem: it is not changing the contents of oldContent, after I perform the function, oldContent contains the exact same HTML (where what should happen is that elements of the class updatable should have different innerText).

Why doesn't the string oldContent change?

    function insertContentIntoUpdatableElements( oldContent, newContent )
{
    // Pre: oldContent & newContent must be strings of HTML returned from jquery's
    //      $("").html()

    try
    {
        alert("BEFORE: "+oldContent);
        var index       = 0;
        var oldElements = $(oldContent).find(".updatable");
        var newElements = $(newContent).find(".updatable");

        $(oldContent).find(".updatable").each( function()
        {
            var txt = $(newElements[index]).text(); alert("TEXT: "+txt); 
            alert("OLD TEXT: "+$(this).text());
            $(this).text(txt);
            index++;

            alert("NEW TEXT: "+$(this).text());  // prints out CORRECT updated/changed text
        });

        alert("AFTER: "+oldContent);   // prints out INCORRECT updated/changed text for each element of class "updatable"
        return oldContent;
    }
    catch(ex) { alert("In insertContentIntoUpdatableElements(): "+ex); return "FAILED"; }
}

1 Answer 1

3

This should do the trick.

  function insertContentIntoUpdatableElements( oldContent, newContent )
  {
    var result = $(oldContent);
    var oldElements = result.find(".updatable");
    var newElements = $(newContent).find(".updatable");

    $(oldElements).each(function(index, el)
    {
      $(oldElements[index]).text($(newElements[index]).text());
    });
    return result;
  }

See a working Demo on jsFiddle: http://jsfiddle.net/ZZVgh/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.