Michael
Michael

Reputation: 4461

Wrap element with div

jquery-3.2.1.min.js

I clone an element and would like the cloned element be wrapped in tag.

function add_and_keeper(){
  let $and_keepers = $("#and_keepers"); // $and_keepers = [td#and_keepers]
  let $keeper_choice_clone = $person_choice.clone() // $keeper_choice_clone = [select#id_person_choice, prevObject: r.fn.init(1)]
  let $wrapped = $keeper_choice_clone.wrap("<div>"); // $wrapped = [select#id_person_choice, prevObject: r.fn.init(1)]
  let $new_elem = $and_keepers.append($wrapped).children("select:last-child");
}  

Well, added is:

<select name="person_choice" id="id_person_choice">
  <option value="" selected="">---------</option>

  <option value="1">1: Smith </option>

  <option value="2">2: Johnson </option>

</select>

As we can see, it is not wrapped with div.

Desired is:

<div><select name="person_choice" id="id_person_choice">
  <option value="" selected="">---------</option>

  <option value="1">1: Smith </option>

  <option value="2">2: Johnson </option>

</select></div>

Could you help me understand where the error is.

Upvotes: 0

Views: 47

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075567

Always best to read the documentation of the method you're using: :-)

This method returns the original set of elements for chaining purposes.

So when you then append it, you remove it from the wrapper and instead put it in its new parent.

Instead, since you're dealing with an element that isn't in the DOM, create the div and add to it with append:

function add_and_keeper(){
    let $and_keepers = $("#and_keepers"); // $and_keepers = [td#and_keepers]
    let $keeper_choice_clone = $person_choice.clone() // $keeper_choice_clone = [select#id_person_choice, prevObject: r.fn.init(1)]
    let $div = $("<div>");
    $div.append($keeper_choice_clone);
    let $new_elem = $and_keepers.append($div).children("select:last-child");
}

That can also be written more concisely if you like:

function add_and_keeper(){
    let $and_keepers = $("#and_keepers"); // $and_keepers = [td#and_keepers]
    let $keeper_choice_clone = $person_choice.clone() // $keeper_choice_clone = [select#id_person_choice, prevObject: r.fn.init(1)]
    let $new_elem = $and_keepers.append($("<div>").append($keeper_choice_clone)).children("select:last-child");
}

I tend to prefer the former for debugging.

Upvotes: 1

Related Questions