简体   繁体   中英

open <div> before element and close it after

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"

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.

你可以使用 .wrap() 用 div 包裹任何元素:

$( "#search" ).wrap( "<div id='id'></div>" );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM