2

I'm wanting to clone a parent element. Currently I've only managed to clone the contents of that element.

$(this).parents('.row').clone();

This returns the contents of .row, how may I clone the .row element?

Fiddle - give the last input a value

ditto
  • 5,917
  • 10
  • 51
  • 88

1 Answers1

5

What you don't include is that you're using .html() in your jsbin code, which is what's actually returning the inner part of the row.

To "combat" this, use a temporary container and do the .html() on the container:

$('<div>').append($(this).parents('.row').clone()).html();

http://jsbin.com/fesicaqotu/1/edit?js,output

Another, perhaps better option, is to use .outerHTML on the dom element and forget the clone altogether:

self.parents('.row')[0].outerHTML;

http://jsbin.com/buhekitiju/2/edit?js,output

Jared Farrish
  • 48,585
  • 17
  • 95
  • 104
  • Digging deeper, it appears the actual issue is that I'm editing the cloned variable, when I do: .find('input').empty().end().html() - it removes the container element. Is there a way to manipulate the cloned variable without losing the container element? – ditto Mar 28 '15 at 14:15
  • Are you trying to clear the value? Use `.find('input').val('')`. [`.empty()`](https://api.jquery.com/empty/) removes nodes belonging to the selected elements, and `input` element have no children. So that's not the issue. With `.html()`, you are still going to get what's inside the selected element, not what's inside wrapped with what's the wrapper included (this is called `outerHTML`, `.html()` is `.innerHTML`, see my edit). – Jared Farrish Mar 28 '15 at 14:18
  • 1
    I see. So something like: var copylast = self.parents('.row')[0].outerHTML.find('input').val(''); ? – ditto Mar 28 '15 at 14:22
  • `outerHTML` is going to give you a string. Do `$(self.parents('.row')[0].outerHTML).find('.input').val('').end();` The alternative would be to do the latter in a separate call, `var copyLast = $(self.parents('.row')[0].outerHTML); copyLast.find('.input').val('');` – Jared Farrish Mar 28 '15 at 14:25
  • Neither of those methods are working, unless I'm doing it wrong? http://jsbin.com/pecehulafo/1/edit?html,css,js,output – ditto Mar 28 '15 at 14:32
  • You have a typo on the line where you append the `copyLast` node (hint: the console tells you why). – Jared Farrish Mar 28 '15 at 14:34