JQuery get the value of the nth element

Good afternoon. I used the search but did not find the answer I was looking for, I think this is a general question.

Is there any solution for getting the value of the nth element via jQuery?

Here is a simple example: Imagine that we have n inputs with one class. The easiest way to get the value of the nth, as I thought, is $(".some_class").get(n-th).val() is the easiest way. But when we use get() , it returns

#HTMLInputElement Object

So, after using val() on it, we got an error:

Uncaught TypeError: Object #HTMLInputElement does not have a 'val' method.

Is there any solution how to use only jQuery methods in this situation?

+4
source share
6 answers

Use eq instead:

 $(".some_class").eq(n-th).val() 

eq creates a new jQuery object from the element specified in the set.

+2
source

You will get a list of the nth element using the nth child, so use val on one of them

 $(".some_class input:nth-child(2)").eq(0).val() 

The nth-child (n) pseudo-class is easily confused with: eq (n), even though the two can lead to significantly different matched elements. Using nth-child (n), all children are taken into account, regardless of whether they are, and the specified element is selected only if it matches the selector attached to the pseudo-class. C: eq (n) only the selector assigned to the pseudo-class is taken into account, not limited to, by children of any other element and the (n + 1) th (n-0) is selected, link

If you just want to get the nth input in the .some_class class, you can just use eq ()

 $(".some_class").eq(0).val() 
+2
source

You can use eq with jQuery

$ ('selector'). Equ ('number')

+1
source
 $("element:nth-child(1)").val(); $("element:nth(0)").val(); $("element:eq(0)").val(); 
+1
source

On the line, use code like:

 $('container').eq('n'); 
+1
source

JQuery () method. get () returns the actual HTML element, not the jQuery object (therefore, it does not have a .val () method). You need to use .value or you need to get the index using [].

eg.

  $(".some_class").get(n-th).value; 

OR

  $(".some_class")[n-th].val(); 
0
source

Source: https://habr.com/ru/post/1499171/


All Articles