Home > UI/UX Development > JavaScript > jQuery: Difference between selectors :first, :first-child and :first-of-type

jQuery: Difference between selectors :first, :first-child and :first-of-type

This post was most recently updated on April 11th, 2019

Definition:

  • :first – use this selector to select first element. This selector select only one single element from all related elements available on the page.
  • :first-child – use this selector to select all first child elements from each parent.
  • :first-of-type – use this selector to select all first child elements, of a specific type, of their parent.

See the difference between these methods with example given below:

HTML:

CODE:

Output:

Click on ‘:first’ button you can see only a ‘P’(paragraph) element with green background colour which is the first paragraph element of the entire page.

Now refresh browser and click on ‘:first-child’ button you can see ‘P’(paragraph) elements with red background colour which are the first child element of their parent element. Here in the first blue border box there is also ‘P’(paragraph) element but it not selected because before the ‘P’(paragraph) there is a ‘SPAN’ element so ‘SPAN’ is first child element of their parent not ‘P’(paragraph).

Now refresh browser and click on ‘:first-of-type’ button you can see ‘P’(paragraph) element with blue background colour which are the first child element of, a specific type, of their parent element.

Click here to check all the above selectors difference.

This Article is TAGGED in , , , , , . BOOKMARK THE permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">