Removing DOM element using jQuery
I have a custom error script that displays custom error messages on a page if a user tries to submit a form and it fails validation.
On the focusout of the input element (the input that failed validation) I am trying to remove the DOM element I added, but its removing all of the DOM elements with the class name I specify that exist on the page.
Adding the DOM element:
$('#' + el).closest('tr').addClass('pink_bg');
var error_txt = $('#' + el).attr('rel');
$('#' + el).before('<span class="regist开发者_JS百科ration_error_message">' + error_txt + '</span>');
Attempting to remove the DOM element (this removes all of the DOM elements of class="registration_error_message"), all I want to do is remove one of the elements:
$("#" + el).focusout(function(){
$(this).parent().remove('[class^=registration_error_message]');
$(this).closest('tr').removeClass('pink_bg red_border');
});
Since you're adding the .registration_error_message
element before the el
element using jQuery's .before()
method, it would seem that you want to use .prev()
instead of using .parent()
when removing.
$(this).prev().remove('[class^=registration_error_message]');
Or
$(this).prev('[class^=registration_error_message]').remove();
You can use a different traversal method to get what you're after. Since you're adding it as a previous sibling with .before()
, use .siblings()
with a .class
selector, like this:
$(this).siblings('.registration_error_message').remove();
//or more specific:
$(this).prev('.registration_error_message').remove();
精彩评论