Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery copy and paste DOM node?

Tags:

jquery

dom

I have a table that looks like the following.

<tr>
  <td>Link Name</td>
  <td><a href="#" class="edit">Edit</a></td>
</tr>

At the bottom of the table I have the following.

<tr>
  <form class="hidden create">
    <h3>Add Link</h3>
    ...
    <input type="hidden" name="form_id" value="{menu-id}" />
  </form>
</tr>

To avoid a massive page of HTML I thought it would be cool if jquery could copy the create form, tweak a few attributes then make it appear after the links row. The only query really is how..

So here are my questions.

1) How do I grab the create form and save it as variable with jquery?

2) How do I edit the hidden field? I know how to change attributes but how do I select the field it once the form is within a variable?

3) How do I paste this form into my table after the edit link on its own row? I need something like parent-parent-after?

Thanks loads

like image 811
JasonS Avatar asked Sep 09 '10 14:09

JasonS


People also ask

How do I copy a DOM element?

The cloneNode() method creates a copy of a node, and returns the clone. The cloneNode() method clones all attributes and their values. Set the deep parameter to true if you also want to clone descendants (children).

How do you clone an object in jQuery?

To clone an element using jQuery, use the jQuery. clone() method. The clone() method clones matched DOM Elements and select the clones. This is useful for moving copies of the elements to another location in the DOM.

How do you copy the content of a div into another div using jQuery?

First, select the div element which need to be copy into another div element. Select the target element where div element is copied. Use the appendTo() method to copy the element as its child.


1 Answers

1) Place a copy of the form in a variable:

var create_form = $('form.create').clone();

2) Get the hidden input from the variable:

create_form.find(':hidden[name=form_id]').doSomething()...

3) Place form after .edit link in the same row (I assume this is in an event handler):

$(this).closest('tr').find('a.edit').after( create_form );
like image 138
user113716 Avatar answered Oct 22 '22 09:10

user113716