20 Impressive jQuery Plugins to Replace the HTML Select Box

The traditional HTML select element is not very powerful out of the box, it lacks in more substantive features. Today, the web demands controls with multiple features for a user-friendly experience and the traditional HTML select box just can’t compete. Features like multi-select, grouping, hierarchical lists, and custom HTML markup make light work of projects and tasks, and the HTML Box lacks these features.
Writing your own implementation for these features will require a lot of effort, and testing browser compatibility can be a nightmare. Luckily, jQuery offers lots of plugins to save you from that hassle. This post has a compiled list of 20 impressive jQuery plugins to replace the traditional HTML select box with a sleek, stylish and feature-rich select box. These jQuery plugins offer various features like changing default styles, adding search functionality, grouping the items, creating hierarchies, keyboard navigation, multiple item selection and many other features.

1. Pretty Dropdowns

Pretty Dropdowns


Pretty Dropdowns is a simple, lightweight jQuery plugin that converts <select> drop-down menus into “pretty” menus that you can skin using CSS. It features:

  • Two arrow styles and sizes to choose from (or add your own style)
  • Easily add icons, thumbnails, and other custom HTML to the menu items
  • Support for multiple-select lists
  • Support for option groups
  • Tooltips (title) carried over at select, option, and optgroup levels
  • Full keyboard navigation (you can even go directly to a menu item by typing its text!)
  • Auto-linked to label (menu will get focus when you click on the label)
  • Accessibility (it plays nicely with screen readers)
  • Sensibility (when you open the menu it does its best to keep the menu items within the viewport)
  • Complete control over the look and feel of the drop-down menu by modifying prettydropdowns.css

2. SelectPick



SelectPick is a fast, simple, customizable, and lightweight jQuery plugin to customize the HTML drop-down box with custom styling. The beauty of this plugin is that it can be applied to any type of HTML, not necessarily just HTML select box. Features include:

  • Possibility to bind to multiple types of HTML elements
  • Customizable data sources
  • Support for Ajax asynchronous access to data
  • Providing options and labelling disable functions
  • Dynamically setting selected items
  • User style customization

3. InputPicker



InputPicker is a jQuery input plugin that converts an input text field into a filterable, multi-column dropdown select box. When initiated this plugin appends a div element below the input box and styles it with the help of default CSS classes. It supports both local data (data array) and removing data sources (JSON) via AJAX requests. The plugin also gives flexibility to developers to change the width and height.

4. Select2



Select2 is a jQuery replacement for traditional select boxes. Select2 gives you a customizable select box with support for searching, tagging, remote data sets, infinite scrolling, and many other highly used options. It features:

  • Over 40 languages and RTL support.
  • Fully skinnable CSS built with Sass and an optional theme for the Bootstrap 3.
  • Full extensibility to work exactly how you want it to
  • Dynamic item creation
  • Support for both modern and legacy browsers

5. Sweet Dropdown

Sweet Dropdown


Sweet Dropdown is a simple jQuery plugin which creates flexible and animated dropdowns in any direction with any kind of content. It also supports adding icons to select items as well as the option to apply dark or light themes for styling. This plugin works in all major browsers.

6. Awesome Select

Awesome Select


Awesome Select is a beautiful and customizable jQuery plugin for transforming the boring select tag into something beautiful and minimal, with animations inspired from Material Design. You are free to change the way the dropdown looks based on your own taste. This plugin also supports immersive mode, which allows you to render the dropdown in a modal window covering the complete screen. The animations are based on CSS3 transform and transition properties.

7. jQuery Dropdown

jQuery Dropdown


jQuery Dropdown is a flexible and cross-device jQuery plugin for replacing HTML selects and multi-level menus with animated select dropdowns. This plugin allows you to create simple, multiple select, nested, grouped and custom HTML content dropdowns. The plugin allows you to override default settings for animation, keyboard navigation, multiple item selection and other default settings.

8. Combo Select

Combo Select


Combo Select is a jQuery plugin that converts a select box into a searchable and keyboard-friendly interface. The plugin creates a div element and styles it using the default CSS. It also attaches the keydown event to capture key strokes for filtering the select. The other advantage of this plugin is that it falls back to native select on mobile and iPad devices. It features:

  • Search and filter, select items
  • Mobile- and tablet-friendliness (fall-backs to native select)
  • Keyboard accessibility
  • Ease of style
  • Data attribute support
  • Support for both numeric and string data types in select
  • Support for implicit style attributes

9. Fuzzy Dropdown

fuzzy Dropdown


Fuzzy-dropdown is a jQuery plugin that converts a select box into a fuzzy searchable dropdown. Fuzzy string matching is a technique for finding strings that match a pattern approximately rather than exactly. Fuzzy-dropdown delegates interactions to the underlying select box. Also, the dropdown is fully navigable via arrow keys. Fuzzy-dropdown by itself does no styling. All the styling is controlled via CSS. This gives you complete freedom to style your dropdown however you want.

10. DDList



DDlist is a lightweight jQuery plugin that allows you to create a stylish dropdown list supporting list options with text, images, and additional description strings. This plugin hides the select element and the list is ‘reconstructed’ by means of a jQuery-generated <ul> list inside a <div> container. The select element options can also be defined via a JSON array object. The plugin comes with a CSS file that contains various classes to present the internal elements and their styles, giving you the option to modify the existing style to match with your website design.

11. ddSlick



Ever wanted a dropdown with images? Well, you now have a plugin for that! ddSlick is a free and lightweight jQuery plugin that allows you to create a custom dropdown with images and descriptions.

  • Adds images and descriptions to otherwise bland drop downs
  • Allows JSON to populate the drop down options
  • Converts your HTML select element to ddSlick
  • Uses Minimum CSS and no external stylesheets to download
  • Supports call-back functions on selection

12. Dropdown Checkboxes

Dropdown Checkboxes


Dropdown checkboxes is a simple jQuery plugin that turns a bootstrap dropdown component into a compact multi-select dropdown list with checkboxes. This plugin creates a hidden input element. When the values are checked and saved, the plugin creates a JSON array of all checked values and assigns the same to the hidden input box. This plugin also allows you to pre-check the checkboxes on page load. When the selected checkbox’s text values goes beyond a certain length, then the plugin truncates the string value for better UI arrangement.

13. Hierarchy Select

Hierarchy Select


Hierarchy Select is a lightweight jQuery plugin which converts the Bootstrap dropdown into a filterable dropdown list. This plugin works well for simple dropdowns and also for hierarchical dropdown, both with the option to search. You need to define an input element just above the select element. The plugin makes use of this input element to create search functionality for the select box. It attaches a keyup event to the input box and responds to keyboard interaction. For searching the text, it makes use of the indexOf() function which returns the position of the first occurrence of a specified value in a string.

14. Selectric



Selectric is a fast, simple, and light jQuery plugin designed to help in stylizing and manipulating traditional HTML selects elements. It also allows you to select multiple elements and add icons to select list items. It features:

  • Keyboard navigation (Up/Down/Left/Right/Word search)
  • Easy customization
  • Permanently visible options box
  • Independence from external libraries (besides jQuery)
  • Word search compatibility with western Latin characters set
  • 10 built-in themes
  • The ability to dynamically add items to select the element
  • Support for various callbacks for customizable handling
  • Options to populate the data via Ajax
  • Support for custom HTML markup

15. Sumo Select

Sumo Select


Sumo Select is a beautiful and cross-device jQuery plugin that progressively enhances an HTML Select Box into a Single/Multiple option dropdown list. The dropdown list can be fully customizable using simple CSS. It can adapt itself according to any device, keeping the User Experience unbroken. It features:

  • Single and Multi-select options
  • Search support
  • Optgroup support
  • Localization support
  • Full customization by simple css
  • Support for almost all devices
  • Intelligent rendering according to device
  • Rendering native Single/Multiple pop-ups on Android, iOS, Windows and other devices
  • Custom postback data format
  • Selected, Disabled, Select All, keyboard navigation and Placeholder support
  • A redesigned UI (No external icons are used now and the color scheme can be controlled by CSS)
  • Easy extendability to allow developers to create new widgets

16. Fast Select



Fastselect is a lightweight plugin for enhanced select elements based on jQuery. It enables responsive, fast, and sensible UI upgrades of selected elements with features like option searching and remote dataset loading. It weighs less than 5KB (minified and gzipped). It provides features like searching, filtering, tagging, single-select, multi-select, autocomplete, and dynamic AJAX content.

17. Selectize



selectize.js is a lightweight plugin for creating a solid and user-friendly select list with clean and powerful APIs. It’s useful for tagging, contact lists, country selectors, and so on. It clocks in at around ~7kb (gzipped). It features:

  • Skinnability – Comes with LESS stylesheets and shims for Bootstrap 2 and Bootstrap 3.
  • Clean API, code, and extensibility
  • Smart Ranking / Multi-Property Searching & Sorting – Options are efficiently scored and sorted on-the-fly
  • Caret between Items – Use the left and right arrow keys to move between items
  • Select and delete multiple items at once
  • RTL supported – Great for international environments
  • Item Creation – Allow users to create items on the fly
  • Remote Data Loading

18. Light Weight Select



This is a super lightweight jQuery plugin that converts a multi-select drop menu into a simple two panel selection interface. The UI is completely controlled via CSS, so you can change the look and feel according to your needs. The plugin size is 4kb after minification, 2kb for the CSS and 2kb for the double arrow icon.

19. BetterSelecter



BetterSelecter is a simple, clean and easy to use jQuery plugin for converting the standard HTML select box into a stylish and sleek searchable select box. The styling is controlled via CSS classes which gives you flexibility to change the design per your requirements. This plugin appends a div element with a span inside to create a searchable select box and display the selected value.

20. SelectMe



selectMe is a jQuery-based select replacement plugin that replaces the large select element into a neat and searchable solution. It can also add a checkbox or radio button to the items for a better way of selecting the item. It supports:

  • Search for specific elements
  • Selecting or unselecting all elements which are currently shown
  • Show only selected elements
  • Optgroups
  • Navigating through elements with arrow keys (up + down)
  • Selecting elements via space key
  • Jumping directly to the search field when pressing a key while navigating in the dropdown


These lightweight and customizable jQuery plugins allow you to turn the normal HTML select elements into stylish and sleek select elements. These plugins offer various powerful features like searching, grouping, custom HTML markup, keyboard navigation, remote data loading, RTL support, multiple item selection, and other small but handy features. The other advantage is that all the plugins use simple CSS classes to style the select elements. This gives flexibility to the developers to override or change the default plugin style to your own style implementation.

Optimize your jQuery selectors for best performance


Over time, the data size has increased for nearly every application. Due to huge amount of data residing in various database servers, performance becomes the most important and integral part of any application. If the page takes lots of time to render the data, it creates a bad impression and results in loss of interest by the end users. There are different places where performance can be increased, including database code, server side code to process the data and client side code.
Application development has also gone through monumental change over time. The client calls REST API and the server automatically sends the data in JSON or some other format. It’s the responsibility of client side code to process and render it for display. Therefore, it’s pretty important to follow best practices for client side code in order to ensure best performance. jQuery is one of the most popular and most used client side libraries, so writing high performance jQuery code is of the utmost importance. One of the key areas of performance improvement is in the methods for selecting and manipulating HTML elements. jQuery selectors allow you to select and manipulate HTML element(s) quite easily. This post shows how to optimize your jQuery selectors for best performance.
Let’s begin!

Before we get into optimization tips, let me first give you a quick overview of the different categories of jQuery selectors. There is no official categorization, but they can be categorized in this way:

• ID selector $(‘#elementID’)
• Tag selector $(‘p’)
• Class selector $(‘.CSSClass’)
• Attribute selector $(‘[type="text"]‘)
• Pseudo selector $(‘:visible’)

Always use ID selector if possible

Accessing DOM is a very expensive operation, so it’s beneficial to minimize effort and time. As we all know, the ID attribute is unique for each HTML element on the page. In JavaScript document.getElementById() is the function that one would use to select the HTML element. It’s the fastest and the best way to select the element because it directly maps to the element. jQuery is a library written on top of JavaScript, which means that it internally calls the JavaScript functions to do the job. When you use ID as a selector in jQuery, it internally calls document.getElementById(). To select the HTML element with elm as ID, the jQuery code looks like this: $(“#elm”);
This method works well in all browsers, so it’s a good choice if you are using an older browser.

Cache your selector

Caching improves the performance of the application. You can cache data or objects for better performance. You can also cache your jQuery selectors for better performance using the ID as your selector (as mentioned in the previous tip). When you don’t cache the selector, jQuery must rescan the DOM to get the element. You may not feel the difference in small applications, but with large applications this becomes very critical. Let’s look at the process of caching objects in jQuery. The following simple line of code caches the selector and stores it in the $elm variable:

var $elm = $("#elm");

Now use the $elm variable instead of using the jQuery ID selector. Like this:

var $elm = $("#elm");

Remember, the scope of a variable is limited to where it is defined. If it is defined as a global variable then you can use it anywhere in the jQuery code, but if it is inside a method the scope will be limited to that particular method only. Global caching is useful for elements which are frequently used in the code.

Define a context with jQuery selectors

By default, jQuery selectors perform their search within the DOM. But while defining the selector, you can pass the context, which limits the searching range for the jQuery selector. In other words, you are instructing jQuery to look into the context rather than beginning the search from the document root. This helps in speeding up the searching process which will definitely improve the performance. Passing the context is optional, but you should use it whenever you can.

Enough theory! Let’s take a look at a practical example. Consider the following HTML code:

<div id=”parent1”>
<div class=”child”> </div>
<div class=”child”> </div>
<div class=”child”> </div>

If you want to select all the div element with child class you can use the following jQuery code:

var $elm = $(".child");

The above code will search for elements with child class starting from the document root. It can be optimized by passing via an alternate selector. Like,

var $parent = $("#parent1");
 var $elm = $(".child", $parent);

This limits the search range, so now searching is limited to the div with ID parent1. The context argument can be a DOM element, a document, or a jQuery object. If you pass context, then jQuery will internally use the find method to retrieve the elements. So the above code is internally converted to:

var $elm = $parent.find(".child");

jQuery first checks if the passed context is a jQuery object. If it is, it calls the find() method on the given context. If the given context is a DOM element, it first converts it to a jQuery object and then executes the find() method. As such, it is better to pass the object as context instead of the DOM element because it will reduce the conversion time.

Don’t repeat your selectors

As mentioned earlier, you can cache the jQuery selectors which prevents you from repeating your selector. jQuery also offers chaining, which allows you to chain multiple methods in a single call. Consider the following jQuery code:

$("div").css("color", "red");
 $("div").css("font-size", "14px");
 $("div").text("New Text!");

Below is the first optimized version using caching:

var $div = $("div");
 $div.css("color", "red");
 $div.css("font-size", "14px");
 $div.text("New text goes here!");

Next is the second optimized version using chaining:

$("div").css({"color", "red", "font-size", "14px"}).text("New text goes here!");

Use class selector wisely

jQuery also provides a CSS class selector which allows you to select elements with a particular CSS class. This is again a very useful and popular selector as it allows you to select multiple elements at once. However, you have to be cautious while using class selector. The following jQuery code will select all the elements with “dummy” class applied to them:


In this case, jQuery has to scan the complete DOM to discover elements with dummy class. As mentioned earlier, traversing DOM is a very expensive process so it’s always better to minimize this effort. In this case, you can pass a tag name to reduce the searching scope. Like this:


The above code tells jQuery to only give me the DIV elements with dummy CSS class applied. Though the class selector works quite well in modern browsers, older browsers have performance issues with class selector. That being said, it’s not always a good choice to add a tag name with class selector. Why?

In this example, jQuery will first search for all elements with class dummy and then filter records to only return those elements that are div elements. So when the dummy class is only meant for div elements, you need to specify the tag name in order to add an extra step of filtering. Keep in mind that this is only useful when the CSS class is applied to different HTML elements like span, paragraph and div.

Be very specific about selectors

Did you know that jQuery selectors are executed from right to left? In other words, the last selector will be executed first when there are multiple selectors. Consider the following example:

$("div.parent .child");

In this example, jQuery will first search for all elements with class child (last selector executed first) and then apply a filter to return only those elements which are div elements with a parent class applied. This is the optimized version:

$(".parent div.child");

Here we are more specific on the last selector, which helps to speed up performance!

Look for an alternative for the Pseudo selector

Pseudo class selectors are CSS selectors with a colon preceding them. They are also available with jQuery - :visible, :checked or :first. Pseudo selectors are useful for selecting elements with different states, or a particular element from a set of elements, but they are slower compared to other jQuery selectors. You should either find a way to replace the pseudo selector or be very specific in using it. Let’s take a look at examples of both. The following jQuery code selects all elements which are visible:


You can be more specific here. Like,


or even better,


Pseudo selectors like :first, :last and :eq allow you to select a particular element from a set of elements. As an example, the following jQuery code will select the first table row using the :first pseudo selector.


The above code can be replaced with better performing code, but first you need to cache the selector (table row in this case).

var tRows=$('tr');

Since jQuery stores this as an array, we can take advantage of it. To get the first table row:

var firstRow=$(tRows[0]);

To get the last element (:last),

var lastRow = $(tRows[tRows.length - 1]);

Or to get any nth row (:eq(n)),

var nRow=$(tRows[n]);


jQuery is an awesome library that makes developers lives simple, but when not used properly it can be the stuff of nightmares! It’s important to write highly optimized and efficient code for better performance and scalability, on any application. This post shows how to write optimized code for jQuery selectors. These optimization tips show the importance of ID based selectors, the advantages of caching the selectors, defining a context to speed up DOM traversal, being very specific about the selector and using class & pseudo selectors wisely. Make a habit of following these tips to get the best performance from your code!

Handling JSON with jQuery

JSON (JavaScript Object Notation) is a way to store information in an organized manner. It is the preferred data-interchange format as its shorter, lightweight, human-readable and requires no tags like XML. This allows faster processing and transmission, and also the serializing and deserializing becomes much faster when compared to XML. JSON returned via REST APIs is used in different ways on the client side. You can populate data in HTML elements, display the JSON on the UI after formatting and convert it to CSV for exporting. This post provides jQuery solutions for formatting the JSON, converting it to CSV format, and showing the JSON data in an HTML table. Let’s begin!

Format JSON in jQuery

Unformatted JSON is not human-readable and most of the time the JSON returned by REST APIs are not formatted, hence can’t be displayed directly on the UI. There are different ways to format it. Either using your own implementation or third-party plugins. Formatting the JSON using jQuery can be done easily and requires only 2 function calls.

  1. JSON.parse() – To parse a JSON string and convert it to a JavaScript object.
  2. JSON.stringify() – Convert a JavaScript object into a string. You can also apply indentation by passing an optional value.

The following jQuery code formats a JSON string:

var jData = '[{"fname":"Mark", "lname":"Wood", "company":"Apple"},' +
'{"fname":"Steve", "lname":"Jones", "company":"Amazon"},' + 
'{"fname":"Bill", "lname":"Peterson", "company":"HP"},' +
'{"fname":"Peter", "lname":"Jacobs", "company":"Dell"}]';

var tmpData = JSON.parse(jData);
var formattedJson = JSON.stringify(tmpData, null, '\t');

Here, the formattedJson variable will have the formatted JSON string, indented using tab. To display formatted JSON on UI, use the <pre> tag only. If you want to display inside a div, you would need to first append the <pre> tag in the div element. Like:


You can check out the demo here.

Convert JSON to CSV

If you want to convert JSON data to CSV for export purpose, the following jQuery code will help you. The following jQuery code defines a function called ConvertToCSV which takes JSON string, converts to CSV and returns it. Since it’s not compulsory to have comma as a delimiter for CSV, the delimiter is passed from outside which helps in changing the delimiter in the future without changing the actual function. The function first converts the JSON data into an array and then loops through the array to create a delimited string.

var jData = '[{"fname":"Mark", "lname":"Wood", "company":"Apple"},' +
  '{"fname":"Steve", "lname":"Jones", "company":"Amazon"},' +
  '{"fname":"Bill", "lname":"Peterson", "company":"HP"},' +
  '{"fname":"Peter", "lname":"Jacobs", "company":"Dell"}]';

var seperator = ',';
var sCSV = ConvertToCSV(jData, seperator);

function ConvertToCSV(jData, delimiter) {
  var arrJSON = typeof jData != 'object' ? JSON.parse(jData) : jData;
  var sReturnVal = '';
  for (var i = 0; i < arrJSON.length; i++) {
    var sLine = '';
    for (var index in arrJSON[i]) {
      if (sLine != '') sLine += delimiter;
      sLine += arrJSON[i][index];
    sReturnVal += sLine + '\r\n';
  return sReturnVal;

You can check out the demo here.
The above function just creates a delimited string, it doesn’t allow you to save it as a .csv file. If you wish to export/download the JSON data into a CSV file with column headings and an optional report title, the following jQuery code provides a solution for the same. The modified function now expects 3 more parameters: report title, flag to display header, and a file name. While calling the function, please consider following things:

  • If you don’t wish to have a report title, pass an empty string.
  • In case you don’t need a column header, pass ShowHeader as false.
  • Pass the file name without the .csv extension.

The function does the following things:

  • First, parses the JSON data in an object, if not already.
  • If report title is not empty, appends the title to the variable.
  • If ShowHeader is true, then loop through the array’s 0th element to get the header columns and then appends them in the variable.
  • Then loop the array to get the data and creates a delimiter separated string.
  • Once the loop is completed, check the variable for any errors. An empty value means the JSON data is not correct. In such a case, it logs the error and exits the function.
  • If everything is correct, then initialize file format. The file format is CSV in this case.
  • Then it creates a temporary anchor tag and appends it to the HTML body with hidden visibility. Assigns the href and download attribute values and calls the anchor click function. Finally, removes it again from the body as it’s no longer needed.
function ConvertToCSV(jData, title, ShowHeader, fileName, delimiter) {
  var arrJSON = typeof jData != 'object' ? JSON.parse(jData) : jData;
  var strCSV = '';
  //Set title first.
  if (title.length > 0)
    strCSV += title + '\r\n\n';
  if (ShowHeader) {
    var headerRow = "";
    for (var index in arrJSON[0]) {
      if (headerRow != '') headerRow += delimiter;
      headerRow += index;
    strCSV += headerRow + '\r\n';
  for (var i = 0; i < arrJSON.length; i++) {
    var sLine = '';
    for (var index in arrJSON[i]) {
      if (sLine != '') sLine += delimiter;
      sLine += arrJSON[i][index];
    strCSV += sLine + '\r\n';
  if (strCSV == '') {
    console.log('Error while converting due to invalid data');
  var uri = 'data:text/csv;charset=utf-8,' + escape(strCSV);
  var link = document.createElement("a");
  link.href = uri;
  link.style = "visibility:hidden";
  link.download = fileName + ".csv";

Call this function on any event to convert the JSON data into a downloadable CSV file like:

ConvertToCSV(jData, "Employee Data", true, "EmployeeReport", seperator);

You can check out the code in action here.

Convert JSON to HTML Table

The following jQuery code will create a table element, populates the table data from JSON data and appends the table element to the HTML body. The function uses jQuery syntax for different table elements like header row and table row. Inside the JSON array loop, it appends the data in appropriate objects, and finally it is added to the HTML body.

function ConvertToTable(jData) {
  var arrJSON = typeof jData != 'object' ? JSON.parse(jData) : jData;
  var $table = $('');
  var $headerTr = $('');

  for (var index in arrJSON[0]) {
    $headerTr.append($(' ').html(index));
  for (var i = 0; i < arrJSON.length; i++) {
   var $tableTr = $('');
    for (var index in arrJSON[i]) {
      $tableTr.append($(' ').html(arrJSON[i][index]));

Here the table formatting needs to be handled via CSS. You can also incorporate the same in this code with slight modifications.
You can check out the code in action here.


This post provides simple solutions for handling JSON on the client side in different ways. The jQuery implementation helps in formatting the unstructured JSON, converting the JSON data into a CSV string or downloadable CSV file with customization and displaying the JSON data in an HTML table. These jQuery codes are not dependent on any third-party plugins, which helps you to modify them as per your need without any hassle.

JavaScript-Equivalent jQuery Code for Simple Tasks


There are developers who love jQuery and there are some who hate jQuery. The benefits of using jQuery now are debatable, but there was a time when solving the cross-browser issue was a nightmare and using JavaScript was painful. If you had been through that phase, you might understand the importance of jQuery. jQuery was born to overcome the biggest issues of JavaScript. Over the years, JavaScript has also evolved but we should be thankful for the fact that modern browsers are also becoming more and more standard-compliant. jQuery is still a powerful library and it can still reduce your efforts for client-side programming.

The aim of this post is not to discourage your use of JavaScript, but rather to give you an insight into how jQuery can help to solve simple tasks compared to JavaScript. jQuery can help in reducing the lines of code and your efforts, lessen cross-browser compatibility issues, result in faster development, and it makes AJAX calls and animations dead simple. To start with, we’ll take a look at the most basic requirements like selecting elements on the page by their ID, class, and tag name and then we will look at some complex examples. Let’s dive in!

Selecting an Element by ID

JavaScript code

document.querySelector('#elmID'); // Modern Way - IE8 and above 
document.getElementById('elmID'); // Older Way 

jQuery code


As you can already see, we’ve used less code to select the element in jQuery.

Selecting an Element by Tag

Consider a use case to select all the paragraph elements on the page:

JavaScript code


jQuery code


Again, shorter code in jQuery!

Selecting Elements by Class Name

To select all elements having dummy CSS class:

JavaScript code

document.getElementsByClassName('dummy'); // Older Way 
document.querySelectorAll('.dummy'); // Modern Way - IE8 and above

jQuery code


We can see a continuing trend of fewer and shorter lines of code in jQuery.

Change Body Background Color on Load

JavaScript code

function changeBackground(color) {
    document.body.style.background = color;
<body onload = "changeBackground('green');" >

jQuery code

$ ('body').css('background-color', 'green');

A single line of code accomplishes what takes four lines of code to accomplish in JavaScript.

Adding a CSS Class to Element

JavaScript code

if (el.classList)
  el.className += ' ' + className;

jQuery code


That’s three fewer lines!

Making an Ajax Call

JavaScript code

function loadValues() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById(“demo”).innerHTML = this.responseText;
    xhttp.open(“GET”, “/api/values”, true);

jQuery code

function loadValues() {
        url: "/api/values",
        type: "GET",
        dataType: "json",
        success: function(data) {
        error: function(response) {

The jQuery version looks much cleaner and more readable, it also offers a better method for error handling.

Making a Simple Fade-Out Animation

JavaScript code

function fadeOut(element) {
    var op = 1; // initial opacity
    var timer = setInterval(function() {
        if (op < = 0.1) {
            element.style.display = ‘none’;
        element.style.opacity = op;
        element.style.filter = ‘alpha(opacity = ’+op * 100 + “)”;
        op -= op * 0.5;
    }, 500);
var element = document.getElementById(‘elm’);

jQuery code


There is no need to judge here who is better: jQuery is the clear winner.


We’ve just seen how jQuery can make life much simpler for easy tasks. Some functionality can be achieved by just one line of code in jQuery that requires 15-20 lines of JavaScript to achieve the same result. jQuery is an awesome library and it’s still very popular among developers. You should consider it as an alternative for fast development and without worrying about cross-browser issues. However, you should also be careful as it's large file to load! 

Using jQuery to Delete All Inline HTML Styling

Inline HTML styling (when the style attributes for a particular element are written within the HTML tag) is not something that’s considered a best practice when it comes to HTML and CSS, and it’s becoming less and less common. You don’t often come across inline styling unless a site’s code hasn’t been touched since the 90s or early 2000s, but it’s certainly not unheard of. If you find yourself trying to do a redesign of an older site that contains inline styling within the HTML, you’ll almost absolutely find that overriding the inline styling can be a huge pain.

Rather than go through every HTML file to remove inline styling, all of your inline styling woes can be eradicated using a very simple jQuery code snippet, which will completely get rid of all of the style attributes that can be found within your HTML tags. To see how it works, take a look at the code snippet below:


The code snippet above uses jQuery to select every single style attribute (using the * selector in combination with the [style] attribute) and, using the .attr method, removes all of the values from the inline style elements by replacing the text with nothing (thanks to those empty quotation marks).

This is a super simple solution to getting rid of inline styling that can save you tons and tons of time and aggravation. If you’re working on a smaller site with less instances of style attributes within the HTML tags, then it might be wiser to just go through and remove them manually, but if you’ve got a big size with inline styling on every single page, then this is a great, super straightforward, and rather lightweight solution that will easily and quickly remove every single instance of inline style attributes so that the site in question can be updated to look its very best.

How to Use jQuery to Dynamically Open Links in New Tabs

Even if you’re a new or beginning developer, you probably know that you can easily make links open in new tabs by using the target attribute with your anchor tags. To make a link open in a new tab, all it takes is to make your HTML look like this:

<a href="/link/" target="_blank"></a>

The target=”_blank” attribute is all you need to make your links open in new tabs. But what if your anchor tags weren’t written this way, and you still want your links to open in new tabs? You can go back through your HTML and hand code it yourself, but if you’ve got a lot of anchor tags this could take you a really long time. Luckily, jQuery is here to save the day.

With jQuery,  you can use some really straightforward snippets to dynamically open all external links in new tabs without having to go through every line of your HTML with a fine-toothed comb. To see the snippet for yourself, check out the code below:

     this.target = "_blank";

That’s it. All it takes are two lines of  jQuery to make sure that all of your external links open in new tabs. The function is triggered by the .click() event method, so the function won’t run unless any of the external links are clicked on, so it’s a pretty lightweight solution. You can see that the snippet above uses the ‘a[@rel$='external']‘ selector. This can be used to select all of the external links, and apply the target=”_blank” attribute to it. But, if you find yourself wanting to select all of the anchor tags on your page, you can remove the rel code and simply use ‘a’ as the selector. You can also use a similar concept to select all links of one class or ID type by placing the class or ID name in the selector.