Search code examples
javascriptjqueryhtmlvariablesclone

How can I copy and modify text from one element to another?


i am new to JQuery and the question I am going to ask is very simple for most of you.

I need to create a paragraph tag with id "original", and with the content "This is the original text." I want to create an empty paragraph tag with id "clone".

I want to Write a script that stores the value of the '#original' text in a variable, replaces the word 'original' with the word 'cloned' in another variable, and places that value in '#clone'.

Result: There will be two paragraphs, one saying "This is the original text." and another saying "This is the cloned text."

Please explain how can i do this as simple as you can :) Thank you in advance.


Solution

  • You will want to make use of the jQuery .text() function which will allow you to store the text content into a variable.

    var originalText = $("#original").text();
    

    Then you can manipulate that variable like so.

    var modifiedText = originalText.replace("original", "cloned");
    

    Then, using the same .text() function, you can write text into the cloned element.

    $("#clone").text(modifiedText);
    

    Here's a working example: http://jsfiddle.net/DLeGa/

    Of course, you could do this all in one line as well.

    $("#clone").text($("#original").text().replace("original", "cloned")); 
    

    Or you could turn it into a reusable function.

    function cloneText(srcSelector, destSelector, stringToReplace, replaceWith) {
      var text = $(srcSelector).text();
      var modifiedText = text.replace(stringToReplace, replaceWith);
      $(destSelector).text(modifiedText);    
    }
    
    // Usage
    cloneText("#original", "#clone", "original", "cloned");