Search code examples
jqueryhtmlclosest

Trying to add content after the closest label but I think i'm wrong


I have a custom form where I need to add some content after a label, see below.

I have these lines of code:

$("input[name='cpy_name']").closest('.control-label').insertAfter('Some text');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="form-group has-feedback" style="display: block;"> 
      <label class="col-sm-2 control-label">Company</label>
      <div class="col-sm-10 col-md-4">
    	  <input type="text" name="cpy_name" class="form-control" maxlength="200" value="">
      </div>
</div>

I thought using 'closest' I'll find the .control-label... Why it's not working, please clarify me.

Which selector I need to use here?

Thank you in adavance,


Solution

  • closest() finds parent nodes only and has-feedback is not an parent node, so try this:

    $("input[name='cpy_name']").closest('.has-feedback').find('.control-label').after(' Some text');
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <div class="form-group has-feedback" style="display: block;"> 
          <label class="col-sm-2 control-label">Company</label>
          <div class="col-sm-10 col-md-4">
        	  <input type="text" name="cpy_name" class="form-control" maxlength="200" value="">
          </div>
    </div>