Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How get parent div

Tags:

jquery

Good day.

<div class="form-group has-success">
  <label class="control-label" for="inputSuccess">Input with success</label>
  <input type="text" class="form-control" id="inputSuccess">
</div>
<div class="form-group has-warning">
  <label class="control-label" for="inputWarning">Input with warning</label>
  <input type="text" class="form-control" id="inputWarning">
</div>
<div class="form-group has-error">
  <label class="control-label" for="inputError">Input with error</label>
  <input type="text" class="form-control" id="inputError">
</div>

I would like that when input lose focus (focusout) in class element div with class form-group add class add, but only one.

For ex. if input with id=inputError loses focus in class element <div class="form-group has-error"> add class add: <div class="form-group has-error add">

And I would like that only in one element with class form-group add class "add".

I use code:

$(".form-control").focusout(function(){

})

but I don't know how get parent div with class form-group...

How make this?

like image 625
Alex N Avatar asked Jul 05 '26 22:07

Alex N


1 Answers

You can use .closest() to find out the nearest ancestor element matching the given selector

$(".form-control").focusout(function(){
    var $div = $(this).closest('.form-group').addClass('add')
})

in you case if the form-group element is always the direct parent of form-control element then you can even use .parent()

$(".form-control").focusout(function(){
    var $div = $(this).parent().addClass('add')
})
like image 65
Arun P Johny Avatar answered Jul 07 '26 11:07

Arun P Johny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!