I am using .after() like below for Form Validation
$("#contactNum").after(
'<span class="invalid-feedback">Please fill up this Field.</span>'
);
I would like to check if this span is present or absent to avoid add this span twice.
You can check if the next element after your contactNum doesn't have particular class i.e invalid-feedback using this add your span tag.
Demo Code :
//using class
if (!$("#contactNum").next().hasClass("invalid-feedback")) {
$("#contactNum").after(
'<span class="invalid-feedback">Please fill up this Field.</span>'
);
}
/*
//using text
if ($("#contactNum").next().text().trim() != "Please fill up this Field.".trim()) {
$("#contactNum").after(
'<span class="invalid-feedback">Please fill up this Field.</span>'
);
}*/
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="contactNum">
<span class="invalid-feedback">Please fill up this Field.</span>
You can simply just check the next span length using next and length and if already have span you can just fill up text otherwise you can insertAfter check below code.
if( !$('#contactNum').next('span.invalid-feedback').length ){
$('<span class="invalid-feedback">Please fill up this Field.</span>').insertAfter($('#contactNum'));
}else{
$('#contactNum').next('span.invalid-feedback').text('Please fill up this Field.');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="contactNum">