Remove Div If Exits After Div And Put Inside The Main Div
Solution 1:
Here is your answer
You are using
$(this).nextAll(".i-icon-div:first").remove();
//$(this) is null in code//if you use .each you can get each element in $(this)Use
$(".error" ).nextAll(".i-icon-div:first").appendTo('.error')
Jquery Code
$('.error').each(function(index, element) {
if($(this).nextAll(".i-icon-div:first").length > 0){
$(this).nextAll(".i-icon-div:first").appendTo($(this))
}
});
For shorter code You can save selected element in variable like
$ele = $(".error" ).nextAll(".i-icon-div:first")
if($ele.length > 0){
$ele.appendTo('.error')
}
Here is jsfiddle which works great http://jsfiddle.net/krunalp1993/e43dk/3/
Hope this helps you :)
Solution 2:
I think you can use the next adjuscent sibling selector
var $error = $('.error');
$('.error + .i-icon-div').appendTo($error)
Demo: Fiddle
Solution 3:
You are probably using $(this) without right context, if statement is not jQuery function where this is using for current element. You can put the required element in some variable and later use it in if condition.
reqDiv = $(".error" ).nextAll(".i-icon-div:first");
if(reqDiv.length > 0){
alert("div exits");
// reqDiv.remove();
or
$('.error').append(reqDiv);
}
Solution 4:
It's better to loop through all your .error and insert the icon after .error-message if it fulfil your requirement like below:
$.each($(".error"), function () {
var firstIcon = $(this).nextAll(".i-icon-div:first"),
errorMessage = $(this).find('.error-message');
if (firstIcon.length > 0) {
firstIcon.insertAfter(errorMessage);
}
})
Post a Comment for "Remove Div If Exits After Div And Put Inside The Main Div"