Selecting First Level Child Using :first-child Selector In jQuery

In jQuery, Tips and Tricks by May 5th, 2013

264 Views

If you have many elements in a web page but need to select only the first one among them and perform your operation on it, what would you do? If you don’t have an answer, then this article is for you. In this article, I am going to share very easy way to perform operations on the first level child of any desired element.  So read on to find out more.

How To Use :first-child Selector

The first-child selector basically selects all elements that are the first child of their parent.

Let’s take a look at a quick example. The following is the HTML Source code used in the examples.

Example 1: Select first level child div and add custom class to it when a button is clicked

Example 2: Select first level child p tag and add custom class to it when a button is clicked

Example 3: Select first level child table cell and add custom class to it when a button is clicked

Simple, isn’t it?

Do you know of any other ways to use the :first-child selector in jQuery? Feel free to suggest by commenting below.