Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the id of the first instance of a class

I have a few input's... Some with classes, some without. The classes are arbitrarily assigned (with ".error", on a failed form submit, to give you an idea).

How do I find the id of the first instance where that class appears?

For example:

<input id="firstName" type="text" name="firstName" class="text" value="" />
<input id="lastName" type="text" name="lastName" class="text error" value="" />
<input id="email" type="text" name="email" class="text" value="" />
<select name="gender" class="error">
    <option value=""></option>
    <option value="male">Male</option>
    <option value="female">Female</option>                          
</select>

As you'll note, there is also an error class on the select tag. So, in this particular case I need to find the id "lastName" since it is the first time that an element appears with the class "error".

Thanks!

like image 334
Eric Avatar asked Dec 17 '12 12:12

Eric


4 Answers

Try this

$('.error').first().attr('id')

As stated in the other answers, using the css selector :first :

$('.error:first').attr('id')

Keep in mind that the result can be undefined if there is no id attribute or no element containing the class 'error'

like image 180
Intrepidd Avatar answered Nov 14 '22 22:11

Intrepidd


you can find it this way:

 $('.error:first').attr('id');
like image 37
Jai Avatar answered Nov 14 '22 21:11

Jai


This should be what you are looking for -

var className = 'error';
$('.' + className + ':first').attr('id');

I'm using the :first selector and the .attr() function.

  • :first - Selects the first matched element.
  • .attr() - Get the value of an attribute for the first element in the set of matched elements.

Looking at the definition of the attr() function, you might not even need to specify :first. However I find that it's always better to be as verbose as you can with selectors. This also improves readability.

Since you have multiple elements of different types with the same class (inputs and selects), I would also recommend specifying the type of element (in this case, an input) -

$('input.error:first').attr('id');
like image 2
Lix Avatar answered Nov 14 '22 23:11

Lix


$('.error').first(); will return the first element with class error.

like image 1
Anshuman Jasrotia Avatar answered Nov 14 '22 23:11

Anshuman Jasrotia