How To Refer To Next & Previous Controls on HTML Page Using jQuery

Friends, in this article, we will see how to refer to previous and next controls present on a HTML page using jQuery.

jQuery provides 2 very useful functions .prev() and .next() to refer to the immediate previous/next sibling of a given control. This is to be noted that these functions limit to the current reference of a DOM element.

From the jQuery documentation:

  • .prev() gets the immediately preceding sibling of each element in the set of matched elements, optionally filtered by a selector
  • .next() gets the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.
Let's see it in action as in the following:
  1. <div id="div1">  
  2.    <input type="text" id="d1t1" />  
  3.    <input type="text" id="d1t2" />  
  4.    <input type="text" id="d1t3" />  
  5. </div>  
  6. <div id="div2">  
  7.    <input type="text" id="d2t1" />  
  8.    <input type="text" id="d2t2" />  
  9.    <input type="text" id="d2t3" />  
  10. </div> 
In the preceding example, you can traverse between textboxes with ID 'd1t1' and 'd1t2' and 'd1t3' or 'd2t1', 'd2t2' and 'd2t3' using the .prev() and .next() functions. You will not be able to traverse between 'd1t1' and 'd2t1' using these functions because they are contained in multiple parent div blocks. However, you can traverse between 'div1' and 'div2' using .prev() and .next() functions because they are immediate siblings.

Considering the same example above, let's see the following jQuery snippet:
  1. <script type="text/javascript" src="//code.jquery.com/jquery-1.10.2.js"></script>  
  2. <script type="text/javascript">  
  3. $(function () {  
  4.    $("#d1t2").focusout(function () {  
  5.       alert($(this).prev().val());  
  6.       alert($(this).next().val());  
  7.    });  
  8. });  
  9. </script>  
In the preceding snippet, I have handled the focusout() event for the TextBox ID "d1t2". We use the .prev() and .next() functions to get the value of the textboxes with ID 'd1t1' and 'd1t3' respectively.

I hope this gives you a brief insight on how the .prev() and .next() functions work. In case you have any questions, let me know.

Keep learning & sharing!