Search code examples
jquerydomjquery-selectors

jquery .next() missing injected form element


I am somewhat stumped by the behaviour of the .next('selector') method when applied to the html:

<form>
   <label for="relayhosts" class="fixedwidth">Relay Host(s)</label>  
   <input style="display: none;" name="relayhosts" value="" type="text">   
   <input class="ip_octet" id="octet_1" type="text">
   <label class="ip_octet_label">.</label>
   <input class="ip_octet" id="octet_2" type="text">
   <label class="ip_octet_label">.</label>
   <input class="ip_octet" id="_octet_3" type="text">
   <label class="ip_octet_label">.</label>
   <input class="ip_octet" id="octet_4" type="text">
</form>

Using $('#octet_1').next('input'); returns no result yet $('#octet_1').next().next(); returns the next input as expected.

I have also tried $('#octet_1').next('input.ip_octet'); and $('#octet_1').next('.ip_octet'); both of which return nothing.

The input and label elements were dynamically generated but as the next.().next() method sees them it would not seem to be an issue with the objects existing in the DOM.


Solution

  • next() returns the next element only if it matches the selector.

    nextAll() on the other hand, searches all the next elements and returns those that matches the selector.

    So, you probably want:

    nextAll('input:first');
    

    (see the :first selector)

    ... or

    nextAll('input').first();
    

    ... depending on personal preference.