jQuery Code Snippets | Selecting elements with jQuery

Showcasing some of the most usefult jquery conde snippets to help ease DOM manipulation.

  1. Selecting elements using the tag name

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

 $('p').text('Hi there');
  1. Selecting elements using class and id attributes

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

$('#myDiv').text('Hi Again');
$('.myDiv').text('Hi Once 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.

  1. Selecting elements using the index using .eq() method In the below example, the first line selects the first div with ‘myDiv’ class followed by a first paragraph selection on the entire web page.
$('.myDiv:eq(0)').text('Hi Again'); // alternative to using .eq() method $('.myDiv')[0]
$('p:eq(0)').text('Hi Again');
  1. 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.

  1. Selecting elements based on text content using :contains

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

$('p:contains(hello)').css('color','yellow');
  1. Selecting input elements based on checked or unchecked state

The below 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.

 $('input:checked').addClass('selected');
  1. 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.

Subscribe to UIUXTEK Newsletter

One update per week. All the latest posts directly in your inbox.