jquery move element to inside new element

时间秒杀一切 提交于 2020-01-06 09:05:30

问题


For example I have code:

HTML:

...<input type="text">...

And I would like get this input (I can have more inputs) and 'insert' in to new created element e.g <div> in the same place.

Result:

...<div><input type="text"></div>...

This code working half correctly, because it inserts input to new element, but with 'copy' all input from page.

jQuery:

$('input').after('<div class="inp_cont"/>').append("div.inp_cont");

I tried with .detach()

$('input').after('<div class="inp_cont"/>').detach().append("div.inp_cont");

This creates a new element, but don't insert input inside.

I haven't idea how resolve my problem.


回答1:


Just use wrap():

$('input').wrap('<div class="inpt_cont"></div>');

$('input').wrap('<div class="inpt_cont"></div>');
div {
  border: 1px solid #000;
  margin: 0.2em;
  padding: 0.2em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input />
<input />
<input />
<input />

If you want to wrap all elements, matched by the same selector, with the same element:

$('input').wrapAll('<div class="inpt_cont"></div>');

$('input').wrap('<div class="inpt_cont"></div>');

$('input').wrapAll('<div class="inpt_cont"></div>');
div {
  border: 1px solid #000;
  margin: 0.2em;
  padding: 0.2em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input />
<input />
<input />
<input />

References:

  • wrap().
  • wrapAll().


来源:https://stackoverflow.com/questions/26495862/jquery-move-element-to-inside-new-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!