jQuery selector with nth-of-type()

2019-08-02 18:12发布

问题:

Using Chrome Development Tools

jQuery('.proejct-text-field')

gives me four instances of HTML Elements:

<div class=".proejct-text-field ...">...<>
<div class=".proejct-text-field ...">...<>
<div class=".proejct-text-field ...">...<>
<div class=".proejct-text-field ...">...<>

Trying the following doesn't return any Elements.

jQuery('.proejct-text-field:nth-of-type(1)')

As for my understanding the first Element should be returned. I just use jQuery in order to find the right selector for my purposes and to take them into my css file. So How can I select the first Elment of those Divs. Btw: They are not wrapped into a certain parent element. So any child methods won't work. Further the number of divs is variable.

回答1:

Your class name is incorrect, you are having a . in the class=".proejct-text-field ...".

Also, you can use .first() to select the very first element like

$('.proejct-text-field').first();

You cannot select nth-of-class because there's no such way to select nth element with a class, so your selector should work though it doesn't because you have to take out the period . from the class name in your DOM)*

Demo

Demo 2 (Using jQuery .first())



回答2:

The nth-of-type selector looks for element type, like div, span etc not for class name or any other selectors

use :eq(index)

jQuery('.proejct-text-field:eq(0)')

or .eq(index)

jQuery('.proejct-text-field').eq(0)


回答3:

First change mark up with this

<div class="proejct-text-field ...">...<> <!-- removed `.` -->

instead

<div class=".proejct-text-field ...">...<> 

And use .first() if you want first

jQuery('div.proejct-txt-field').first();


回答4:

The :nth-of-type() selector "Selects all elements that are the nth child of their parent in relation to siblings with the same element name." - But you indicated that your elements are "not wrapped into a certain parent element", i.e., they have no particular relationship with each other.

If you just want the first element with that class do this:

jQuery('.proejct-text-field').first()
// or
jQuery('.proejct-text-field').eq(0)
// or
jQuery('.proejct-text-field:first')
// or
jQuery('.proejct-text-field:eq(0)')

Note that you should remove the . from the class name in your class="" attribute in the markup. I.e., it should be:

class="proejct-text-field"

(And you've spelled "project" incorrectly everywhere.)



回答5:

Firstly, you have a . in your class Name, that's unnecessary... Just make it proejct Instead of nth-of-child, use :eq, like this

<div class="proejct-txt-field"></div>

and your jQuery

jQuery('.proejct-text-field:eq(0)');

or

jQuery('.proejct-txt-field').first();