Reputation: 149
I'm creating a JQuery Plugin.
I need to add automatically add a <div id="id">
before some code and the </div>
after.
When i do it with $('#search').before('<div id=id>')
the div automatically close...
this is the code:
<div id="id"></div>
<input type="text"value="" id="search"></input>
<select id="select"></select>
<table id="table"></table>
<div id="current"></div>
<div id="pagination"></div>
i need to open a "div" before "#search" and close it after "#pagination"
Upvotes: 3
Views: 2311
Reputation: 337570
The issue with your current code is that you can only insert whole elements in to the DOM, that is to say an element which includes its closing tag should it require one.
To achieve what you want you can use wrapAll()
after selecting all the required elements:
$('#search, #select, #table, #current, #pagination').wrapAll('<div id="id" />');
#id {
border: 1px solid #C00;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<input type="text" value="" id="search" />
<select id="select"></select>
<table id="table">
<tr>
<td>#table</td>
</tr>
</table>
<div id="current">#current</div>
<div id="pagination">#pagination</div>
You could make this easier to maintain by putting the same class on all those elements instead of selecting them all individually.
Upvotes: 6
Reputation: 5049
You can use .wrap() to wrap any element with div:
$( "#search" ).wrap( "<div id='id'></div>" );
Upvotes: 2