open <div> before element and close it after

情到浓时终转凉″ 提交于 2021-02-09 11:12:35

问题


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"


回答1:


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" />');

Working example

You could make this easier to maintain by putting the same class on all those elements instead of selecting them all individually.




回答2:


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

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


来源:https://stackoverflow.com/questions/37206070/open-div-before-element-and-close-it-after

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