Register to get access to free programming courses with interactive exercises

JQuery JS: DOM API

In August 2006, John Resig released the JQuery library. In a short time, this library has gained huge popularity and has become the de facto standard for the development of interactive elements on websites.

// The $ sign is a jQuery function, through which everything is done
$(() => {
  // This function will be executed on the DOMContentLoaded event
});

In many ways, this happened because jQuery appeared at the right time in the right place. At that time, people were transitioning to layouts that didn't use tables, and CSS was starting to be used more and more actively and more diversely. jQuery allowed developers to reuse the same selectors to add behavior.

In addition, CSS3 was implemented in jQuery much earlier than it appeared natively in the browsers themselves. Moreover, jQuery meant that people practically didn't even have to think about different browsers, since its task was largely to ensure that websites worked on all platforms.

// Works the same way as document.querySelectorAll
// document.querySelectorAll('.section span')
// Returns a special jQuery collection with its own set of methods
const spans = $('.section span');

Another reason for its success was that jQuery popularized the separation of layout and behavior. This technique is called “unobtrusive JavaScript”. The idea is that event handlers are defined not in the tags themselves, but separately:

const buttons = $('button');
// Hangs a click handler on all buttons in this collection
buttons.click(() => {
  alert('hey!');
});

Instead of:

<button onclick="alert('hey!')">

jQuery itself is an excellent example of a DSL (domain-specific language). As a rule, the jQuery code expresses the task in the same terms in which it's formulated:

// Hiding all elements with the container.main selector
$('container.main').hide();

// Deleting an element with id=address
$('#address').remove();

And that's not all. jQuery has long provided the only decent way to make AJAX requests and animations on pages. And thanks to its extensibility provided by plug-ins, the library ecosystem has over the course of a dozen or so years become absolutely fantastic. At one point, any frontend library would have appeared as a plugin for jQuery. To the point that some people don't even know about the existence of JavaScript and DOM. They immediately started with jQuery and see the world only through it and it only.

Manipulations

The $ function is a single entry point for everything. If you call it and pass a string inside, then jQuery thinks that the string is a selector, and that you need to fetch DOM elements. This call is similar to thequerySelectorAll() call, with the only difference being that a specialized collection is returned.

In principle, jQuery works with elements in the same way as with collections, even if it's just a single element. And any changes are applied immediately to all elements of the collection, without the need for any iteration.

// All h1 elements are selected
const headings = $('h1');
// Adding a class to all h1 headers
headings.addClass('header');

// The same without jquery
const headings = document.querySelectorAll('h1');
headings.forEach((el) => el.classList.add('header'));

Below are some examples of functions that modify the DOM element and its descendants. The main feature of jQuery here is that if you call these functions without parameters, they return a value, and if they're called with parameters, they change.

// If one header was found
const link = $('#home');
link.html('link to home'); // installing textContent
link.attr('href', '/about'); // setting the attribute
// reading the attribute
console.log(link.attr('href')); // => /about

Events

jQuery provides its own methods for subscribing to events, acting as an abstraction for addEventListener. For example, this is how a click on a button will be processed:

$('button').click(() => {
  // Setting the href attribute on an element with the w3c ID
  // attr can take a function as the second parameter. The original attribute value is passed to it
  $('#w3c').attr('href', (i, origValue) => `${origValue}/jquery`);
});

AJAX

jQuery can also execute Ajax requests. However, it learned to do this before standards arrived, so the interface of this mechanism differs from standard promises.

// The call chain works on the same principle as promises,
// although it differs in terms of details
const jqxhr = $.get('/api/v1/companies.json', (data) => {
  console.log('success');
})
.done(() => {
  console.log('success');
})
.fail(() => {
  console.log('fail');
})
.always(() => {
  console.log('finished');
});

Animation

jQuery, provides a set of ready-made animations, and it also provides a mechanism for creating more complex effects based on changing CSS properties.

<!-- The element looks smooth when clicked -->
<div id="clickme">
  Click here
</div>
<img id="book" src="book.png" alt="" width="100" height="123">
<script>
  // he #book element loads as hidden, and appears slowly when clicked 
  $('#clickme').click(() => {
    $('#book').show('slow', () => {
      // Actions after the animation is completed
    });
  });
</script>

A group of jQuery UI plugins has been implemented forJQuery UI, which implements some typical functionality needed when developing interactive sites, for example, dragging, autocompleting, resizing, sorting, and various other things.

JQuery UI

Prospects

At one time, jQuery was a great choice, but that's not always the case anymore. Since the release of the library, the web has marched on. The DOM standard has evolved so much that it's more convenient to do many things directly than it is through jQuery, and there's a lot of support from browsers for the standard itself. In places where there isn't enough support, there are always polyfills. In addition, there are new standards that jQuery doesn't fit into. An obvious example would be promises and AJAX.

All of this is leading to jQuery gradually being abandoned. You can find many popular libraries for any frontend task that will be better in their niche than what jQuery offers.

On the other hand, there is already so much written on jQuery that it's more or less required knowledge for any vacancy related to frontend development. As illustrated by the examples above, there's nothing complicated or fantastic about jQuery. Moreover, knowing the DOM is the most important thing, and everything else is just about carefully reading documentation and looking at examples of it being used.


Hexlet Experts

Are there any more questions? Ask them in the Discussion section.

The Hexlet support team or other students will answer you.

About Hexlet learning process

For full access to the course you need a professional subscription.

A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.

Get access
130
courses
1000
exercises
2000+
hours of theory
3200
tests

Sign up

Programming courses for beginners and experienced developers. Start training for free

  • 130 courses, 2000+ hours of theory
  • 1000 practical tasks in a browser
  • 360 000 students
By sending this form, you agree to our Personal Policy and Service Conditions

Our graduates work in companies:

<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.bookmate">Bookmate</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.healthsamurai">Healthsamurai</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.dualboot">Dualboot</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.abbyy">Abbyy</span>
Suggested learning programs

From a novice to a developer. Get a job or your money back!

Frontend Developer icon
Profession
beginner
Development of front-end components for web applications
start anytime 10 months

Use Hexlet to the fullest extent!

  • Ask questions about the lesson
  • Test your knowledge in quizzes
  • Practice in your browser
  • Track your progress

Sign up or sign in

By sending this form, you agree to our Personal Policy and Service Conditions
Toto Image

Ask questions if you want to discuss a theory or an exercise. Hexlet Support Team and experienced community members can help find answers and solve a problem.