4

I'm trying to copy the contents of an element using elem.html() but it's not including the contents of inputs or textareas.

Here's an example (try writting in the boxes then click "Copy"): http://jsfiddle.net/gAMmr/2/

Is there a way of copying all info?

These are the approaches I have tried so far:

  • elem.clone() - not suitable for my task because it copies the element itself
  • elem.children().clone() - misses out text nodes
  • elem.contents().clone() - doesn't include the textarea contents

EDIT: The results seem to be different in each browser. I'm using Chrome.

Nick Brunt
  • 9,533
  • 10
  • 54
  • 83

4 Answers4

5
$("button").click(function () {
    $("#2").html($("#1").html());
    $("#1").find("input").each(function(idx) {
        $("#2").find("input").eq(idx).val($(this).val());
    });
    $("#1").find("textarea").each(function(idx) {
        $("#2").find("textarea").eq(idx).val($(this).val());
    });
});

http://jsfiddle.net/gAMmr/5/

Blazemonger
  • 90,923
  • 26
  • 142
  • 180
  • 3
    @mblase I **strongly recommend against** `$("#2").html($("#1").html())`. Do this instead: `$('#1').contents().clone().appendTo('#2');` – Šime Vidas Sep 12 '11 at 18:13
  • @Nick `$("#2").html($("#1").html())` - this will serialize (stingify) the *NodeList* that represents the children of `#1`, only to parse that HTML string back into a *NodeList* in order to attach those nodes to the `#2` element. This process can be compared to having a digital signal converted to an analog signal, and than back to a digital signal. You don't wan to do that. To avoid serialization / deserialization, clone the elements. – Šime Vidas Sep 12 '11 at 18:24
  • @mblase No, that's not the reason. [Read here](http://stackoverflow.com/questions/7392930/why-should-y-innerhtml-x-innerhtml-be-avoided) why it should be avoided. – Šime Vidas Sep 12 '11 at 20:45
  • Sime: I like how you went to ask all of SO how to contradict me. :-) – Blazemonger Sep 12 '11 at 20:46
  • is the `clone()` still not fixed in jQuery? I don't understand https://bugs.jquery.com/ticket/3016 – basZero Feb 09 '17 at 09:18
3

As Šime Vidas pointed out earlier, this is a 4-year old bug which hasn't been corrected, though a fix exists which is quite simple to apply:

-Download jquery.fix.clone.js
-Include it in your page: <script src='path/to/jquery.fix.clone.js'></script>

From then on cloned textarea elements should include the text of their source (note: you need to use the .clone() method to create your new textarea, not .html()).

Max
  • 12,794
  • 30
  • 90
  • 142
2

Inputs don't contain HTML, they have values. Use .val() for form elements.

Diodeus - James MacFarlane
  • 112,730
  • 33
  • 157
  • 176
0

How about checking the type of the element you're trying to grab the inner text from and if it's an input or textarea use $.text() instead of $.html()

Bassem
  • 3,135
  • 2
  • 25
  • 41