jQuery indexof() Method

Shraddha Paghdar Oct 12, 2023
jQuery indexof() Method

In this article, we’ll tackle the jQuery indexOf capability, which returns a position of the specified element or character within the specified elements or string.

Use the indexOf Method in jQuery

The jQuery array function indexOf() is used to return the index of the first occurrence of a given element or search value in a given array. The jQuery array function indexOf() is a built-in jQuery function.

The jQuery array indexOf() function finds the specified search value/element in the specified array. If the value/element is found, it returns the first occurrence of the element as an integer value from the left, and it returns -1 if the element is not found in the array,

The search for the element can also be started from the specified index or position. If the starting index is not specified, the search starts from the beginning, index 0 by default.

To start a search at the end, we can use jQuery’s lastIndexOf() function.

Syntax:

array.indexOf(searchValue, initPosition);
  1. searchValue is a mandatory parameter. It indicates the searchValue, which is to search in an array.
  2. initPosition is an optional parameter. It indicates the index value from where the search for the element is to start.

The index value of the specified element will be returned as an output of this function. Let’s understand it with a simple example.

Code - HTML:

<select id="index">
  <option>Japanese</option>
  <option>English</option>
  <option>Hindi</option>
  <option>French</option>
  <option>Telugu</option>
</select>

Code - JavaScript + jQuery:

const languages = ['English', 'Hindi', 'Japanese', 'Marathi', 'French'];
$('#index').on(
    'change', () => {console.log(languages.indexOf($('#index').val(), 0))});

We have already defined the languages ​​in random order in the above example, and once the user selects one of the languages, it tries to find the index of the language in the existing array. This is most useful when this data comes in dynamically.

Try running the code snippet in any browser that supports jQuery. It will show the result below when selecting Hindi or French, respectively.

Output:

1
4

Run Demo Code

Shraddha Paghdar avatar Shraddha Paghdar avatar

Shraddha is a JavaScript nerd that utilises it for everything from experimenting to assisting individuals and businesses with day-to-day operations and business growth. She is a writer, chef, and computer programmer. As a senior MEAN/MERN stack developer and project manager with more than 4 years of experience in this sector, she now handles multiple projects. She has been producing technical writing for at least a year and a half. She enjoys coming up with fresh, innovative ideas.

LinkedIn

Related Article - jQuery Method