healer healer - 1 year ago 92
HTML Question

Finding the closest span with a specific class inside a div

I want to find the closest

with class
. How can I do that using jQuery?

<div class="form-group row">
<div class="col-sm-4">
<label for="reimburse_price" class="control label">Amount</label>
<div class="col-sm-8">
<input type="text" name="reimburse_price" min="1" placeholder='0.00' class="form-control numberOnly" id="reimburse_price" required>
<span class="small text-danger error_span"></span>

My javascript is here


My jquery function is here

function checkNumInput(id){
if ($(id).val() == "") {
$(id)[0].setCustomValidity('Please fill out this field');
$(id).closest("span .error_span").text("Please fill out this field").removeClass("hidden").addClass("text-danger");

Answer Source

The issue with your current code is that closest() looks at parent elements, yet the span you want to find is a child of a parent's sibling to the input.

To solve your issue traverse to a common parent of both the input and span and use find() from there. Try this:

$("#reimburse_price").blur(function() {
    checkNumInput('#' + this.id);

function checkNumInput(id) {
    var $input = $(id);
    if ($input.val() == "") {
        $input.get(0).setCustomValidity('Please fill out this field');
        $input.closest('.form-group').find('.error_span').text("Please fill out this field").toggleClass("hidden text-danger");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download