最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - open <div> before element and close it after - Stack Overflow

programmeradmin0浏览0评论

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"

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"

Share Improve this question asked May 13, 2016 at 9:19 Il_SapoIl_Sapo 1491 silver badge9 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

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./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.

You can use .wrap() to wrap any element with div:

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

评论列表(0)

  1. 暂无评论