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!
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'
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');
$('.error').first();
will return the first element with class error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With