问题
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