簡體   English   中英

使用jQuery在DIV中包裝兩個HTML元素

[英]Wrap two HTML elements in DIV with jQuery

我正在嘗試將兩個元素包裝在div周圍,但是我的代碼無法正常工作。 這是我的HTML:

<div class="form-group requiredField">
  <label for="password" class="col-sm-3 control-label">Password</label>
  <input type="password" class="form-control" id="password" name="password">
  <span class="help">help text</span>
</div>

這是我想要的HTML外觀:

<div class="form-group requiredField">
  <label for="password" class="col-sm-3 control-label">Password</label>
  <div class="col-sm-9">
    <input type="password" class="form-control" id="password" name="password">
    <span class="help">help text</span>
  </div>
</div>

如您所見,我正在嘗試將inputspan標簽包裝在<div class="col-sm-9"> 我嘗試使用以下jQuery代碼段,但無濟於事:

//This only wraps the span
$("#form-group input").next().wrap('<div class="col-sm-9">');

我也嘗試過這個:

//This only wraps the input
$("#form-group input").wrap('<div class="col-sm-9">');

注意:除您自己的答案外,大多數答案都不適用於多個form-group

您的目標似乎是將除標簽外的所有子元素包裝到一個子div中。 如果是這樣,一種簡單的方法實際上是使用:not排除標簽,然后使用wrapAll

$('.form-group').each(function(){
    $(':not(label)', this).wrapAll('<div class="col-sm-9"></div>');
});

JSFiddle: http : //jsfiddle.net/6by51ytL/1/

注意:如果您在form-group有更深層的嵌套子級,請添加直接子級選擇器( > ):

$('.form-group').each(function(){
    $('>:not(label)', this).wrapAll('<div class="col-sm-9"></div>');
});

您可以使用多個選擇器選擇兩個元素,然后

$(".form-group").find('input, span').wrapAll('<div class="col-sm-9">');
//class selector is used for `form-group`

 $(".form-group").find('input, span').wrapAll('<div class="col-sm-9">'); 
 <script type="text/javascript" src="//code.jquery.com/jquery-1.10.1.js"></script> <link rel="stylesheet" type="text/css" href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.2.0/css/font-awesome.min.css"> <link rel="stylesheet" type="text/css" href="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.2.0/css/bootstrap.css"> <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.2.0/js/bootstrap.js"></script> <div class="form-group requiredField"> <label for="password" class="col-sm-3 control-label">Password</label> <input type="password" class="form-control" id="password" name="password" required="" style="width:50%;"> <span class="help">help text</span> </div> 

嘗試以下代碼使用

使用jQuery .nextAll().wrapAll()

的HTML

<div class="form-group requiredField">
  <label for="password" class="col-sm-3 control-label">Password</label>
  <input type="password" class="form-control" id="password" name="password">
  <span class="help">help text</span>
</div>

jQuery的

$('.control-label').nextAll().wrapAll('<div class="col-sm-9" />');

JSFIDDLE演示

我想到了。 該代碼對我有用:

$('.form-group input').each(function () {
    $(this).next('span.help').andSelf().wrapAll('<div class="col-sm-9">');
          });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM