如何在主div之后追加div
jQuery代码
var $icons = $('.error + .i-icon-div');
if ($icons.length) {
$icons.each(function () {
var $this = $(this);
$this.appendTo($this.prev())
})
}
Html代码
<div class="error">
<input type="text" name="email" />
<div class="error-message">Please Enter Email</div>
</div>
<div class="error">
<input type="text" name="email" />
<div class="error-message">Please Enter Email</div>
</div>
<div class="i-icon-div">Lorem Ipsum</div>
输出
<div class="error">
<input type="text" name="email" />
<div class="error-message">Please Enter Email</div>
</div>
<div class="error">
<input type="text" name="email" />
<div class="error-message">Please Enter Email</div>
<div class="i-icon-div">Lorem Ipsum</div>
</div>
需要那样的输出
<div class="error">
<input type="text" name="email" />
<div class="error-message">Please Enter Email</div>
</div>
<div class="error">
<input type="text" name="email" />
<div class="i-icon-div">Lorem Ipsum</div>
<div class="error-message">Please Enter Email</div>
</div>
我在这里讨论了类似的Remove div if exits after div and put inside the main div
答案 0 :(得分:3)
尝试在此处使用insertBefore(),以便您可以更改:
$this.appendTo($this.prev());
为:
$this.insertBefore($this.prev().find('.error-message'));
答案 1 :(得分:0)
使用~
而不是+
var $icons = $('.error ~ .i-icon-div');