jQuery Code Snippets | Selecting elements with jQuery

Author Purushothaman Raju ,Posted on June 05 2020

1. Selecting elements using the tag name

 $('p').text('Hi there');

The above is an example of element selection, We select all Paragraph elements in the page and sets the inner text of paragraphs to “Hi there”

2. Selecting elements using class and id attributes

$('#myDiv').text('Hi Again');
$('.myDiv').text('Hi Once Again');

The above code is to select using ID and Class note the use #(pound) and . (dot) the represent the CSS way of targeting elements

3. Selecting elements using the index using .eq() method

$('.myDiv:eq(0)').text('Hi Again'); // alternative to using .eq() method $('.myDiv')[0]
$('p:eq(0)').text('Hi Again');

In the above example, the first line selects the first div with ‘myDiv’ class followed by a first paragraph selection on the entire web page.

4. Selecting elements using attributes

$('input[type="text"]').value('Hello');
$('a[href="#"]').css('color','grey');

The above example is what is known as an attribute selection in jQuery the first line of code selects all input fields with type text and sets its value to hello. The second line selects all anchor tags with href of # and sets its color to Grey.

5. Selecting elements based on text content using :contains

$('p:contains(hello)').css('color','yellow');

The above selector finds all paragraph elements which contain a string hello in them and adds a CSS property of color with the value of yellow.

6. Selecting input elements based on checked or unchecked state

 $('input:checked').addClass('selected');

The above code snipper selects all input elements which are checked this would mostly be checkboxes and radio buttons, once the inputs are selected we then add a class to it.

7. Using the .parent() method to select elements

$('p').parent().addClass('parent-container');
$('p').parent('div').addClass(parent-div-container);

The above code snippet on line 1 selects the immediate parent of the paragraph and adds a CSS class to it, the next snippet in line 2 selects only the parent element which is a div. we can also chain these methods like these.

 $('p').parent().parent()

this will select parent’s parent of the paragraph element



There are several ways of selecting elements in jQuery so this post will be updated frequently to add more element selection techniques using jQuery as a tip remember most of the CSS element selection can be used with jquery to select elements.