Advertisement
  1. Code
  2. JavaScript
  3. jQuery

12 Helpful jQuery Methods You Should Be Using

Scroll to top

Anyone who has done some web development over the last decade and a half has definitely heard about jQuery. This library did excellent work when it came to taking care of browser inconsistencies. You also had to write significantly less code compared to pure JavaScript in order to get something done. The large ecosystem of plugins around jQuery was also very helpful.

The regular improvements in web standards over the years mean that we no longer have to worry about browser inconsistencies. We also have to write a lot less code to get things done in pure JavaScript now compared to earlier days. However, jQuery is still used in a lot of places. For example, WordPress still ships with jQuery, and it makes sense to use the library if it is already being loaded.

In this tutorial, you will learn about 12 helpful jQuery methods that you could start using in your projects.

Attaching and Removing Data From DOM Elements

Let's begin with some methods that you can use to attach data to any DOM elements or remove attached data from a DOM element.

Using the data() Method

You can easily attach arbitrary data to any element in the DOM by using the jQuery data() method. The same method can also be used to retrieve an attached data value by simply passing a key that represents the name of the data stored. Here is an example:

1
$("div.ba").data("color", "Blue");
2
3
$("div.ba").data("cost", 5);
4
5
$("div.ba").data({
6
  "sold-in-bulk": false,
7
  "volume (in ltr)": 3000
8
});
9
10
let data_object = $("div.ba").data();
11
12
for(let key in data_object) {
13
  console.log(`${key} : ${data_object[key]}`);
14
}
15
/* Outputs:

16
color : Blue

17
cost : 5

18
soldInBulk : false

19
volume (in ltr) : 3000

20
*/

There are a few things that I would like to mention here.

Passing an object to the data() method resulted in the complete replacement of all data in earlier versions of jQuery. However, it now merges the new passed data with the existing data.

Any key names which contain a lower case character after - are replaced by an uppercase letter, as shown in the code snippet above.

This method does not affect the data-* attributes of the calling DOM element. However, the first call to the data() method will result in the retrieval of the values of all data attributes. They are not accessed or modified later.

Using the removeData() Method

This method is useful when you want to get rid of values that were previously set using the .data() method. You can pass a string or an array of key names to this method to remove a particular piece of data. It will remove all values if no key is passed.

This method does not have any effect on the value of data attributes.

Wrapping DOM Elements With HTML

jQuery has three nice methods that you can use to wrap your provided HTML structure around a selected set of elements. Let's consider the following markup as an example:

1
<li>First List Item.</li>
2
<li>Second List Item.</li>
3
<li>Third List Item.</li>

Using the wrap() Method

The wrap() method accepts a selector, an HTML string, or an element as its parameter. This parameter defines our wrapping HTML structure. This structure wraps around every element that is matched by the provided selector.

The important thing to remember here is that the HTML structure can be arbitrarily deep, but it can only have one innermost element.

You can also pass a callback function to this method. The callback function has to return the wrapping HTML content, which will be placed around our set of matched elements.

We could call the wrap() method on our list of items as shown below:

1
$("li").wrap("<ul></ul>");

The resulting markup would look like:

1
<ul><li>First List Item.</li></ul>
2
<ul><li>Second List Item.</li></ul>
3
<ul><li>Third List Item.</li></ul>

As you can see, each individual li tag was wrapped in its own ul tag.

Using the wrapAll() Method

The wrapAll() method works just like the wrap() method. The only difference here is that it will wrap our provided HTML structure around all the matched elements at once.

Let's say we call the wrapAll() method on our original list of items:

1
$("li").wrapAll("<ul></ul>");

The resulting markup would look like:

1
<ul>
2
    <li>First List Item.</li>
3
    <li>Second List Item.</li>
4
    <li>Third List Item.</li>
5
</ul>

Starting from jQuery 3.0, the callback function passed to wrapAll() will only be called once and will refer to the first element in the set. In the previous versions, it was called for every matched element in the set.

Using the wrapInner() Method

The wrapInner() method is useful when you want to wrap the content of each element in the set of matched elements in your provided HTML structure. You can also pass a callback function to this method, which will return the HTML structure that you want to wrap around the content of each element.

This time, we will call the wrapInner() method on each of our list items:

1
$("li").wrapInner("<p></p>");

The resulting markup would look like:

1
<li><p>First List Item.</p></li>
2
<li><p>Second List Item.</p></li>
3
<li><p>Third List Item.</p></li>

As you can see, the wrapInner() method wrapped the content of the li tags inside our provided HTML structure.

The following CodePen demo will show all of these methods in action. Click the Add Wrappers button to add all the wrappers.

Traversing the Next and Previous Siblings in the DOM

The jQuery library offers a lot of methods to easily traverse throughout the DOM. In this section, I will cover four useful methods that you can use to traverse the siblings of your specified element.

Using the nextAll() Method

The nextAll() method returns a list of all the siblings that come after your selected element. You can also pass an optional selector to this method to get only elements that have the specified selector.

Using the nextUntil() Method

The nextUntil() method returns a list of all following siblings up to but not including the element matched by the selector passed to this method as the first argument. A second argument passed to this method can further filter the following siblings based on the provided selector expression.

Using the prevAll() Method

The prevAll() method is similar to nextAll(), but it gives you a list of all the preceding siblings of the calling element. Passing an optional selector as an argument to this method will filter the preceding siblings to remove all elements which do not match the selector.

Using the prevUntil() Method

The prevUntil() method returns a list of all preceding siblings up to but not including the element matched by the selector passed to this method as the first argument. You can also pass a second argument to filter the preceding siblings and only get the ones that match your specified selector.

You can see all these methods in action in the following CodePen demo. I have added uniq as a class to our fifth list element, Antarctica. We will be calling all our methods on this element. The list items in the third and eighth positions have the stop class attached to them. We will use these elements as our stopping point for the nextUntil() and prevUntil() methods.

Clicking the Next All button will turn all our list elements green. However, clicking on the Next Until button will only add an underline to list items six and seven. This is because the eighth element has the class stop.

Quick DOM Replacement

DOM replacement becomes incredibly easy with the help of two helper methods in jQuery.

Using the replaceWith() Method

This method accepts a single parameter that specifies the new elements which will replace the set of matched elements. The return value of this method is the set of elements that was removed.

Here is a simple example where we replace some list elements with our passed element:

1
/* Original HTML

2
<ol>

3
    <li>Albania</li>

4
    <li>Austria</li>

5
    <li class="replace">Gambia</li>

6
    <li>Bhutan</li>

7
    <li>Chile</li>

8
    <li class="replace">Colombia</li>

9
    <li>Cyprus</li>

10
</ol>

11
*/
12
13
$("li.replace").replaceWith("<li>Belgium</li>");
14
/* New HTML

15
<ol>

16
    <li>Albania</li>

17
    <li>Austria</li>

18
    <li>Belgium</li>

19
    <li>Bhutan</li>

20
    <li>Chile</li>

21
    <li>Belgium</li>

22
    <li>Cyprus</li>

23
</ol>

24
*/

Using the replaceAll() Method

This method works pretty much like the replaceWith() method. However, the set of matched elements now replaces the old elements, which are passed as a parameter to this method. Keep in mind that using this method will result in the removal of all the data and event handlers that were tied to the removed elements.

1
/* Original HTML

2
<ol>

3
    <li>Albania</li>

4
    <li>Austria</li>

5
    <li class="replace">Gambia</li>

6
    <li>Bhutan</li>

7
    <li>Chile</li>

8
    <li class="replace">Colombia</li>

9
    <li>Cyprus</li>

10
</ol>

11
*/
12
13
$("<li>Belgium</li>").replaceAll("li.replace");
14
/* New HTML

15
<ol>

16
    <li>Albania</li>

17
    <li>Austria</li>

18
    <li>Belgium</li>

19
    <li>Bhutan</li>

20
    <li>Chile</li>

21
    <li>Belgium</li>

22
    <li>Cyprus</li>

23
</ol>

24
*/

Filtering a Set of Matched Elements With .slice()

Using the slice() Method

Let's say you have a set of matched elements in jQuery, but you only want to work with a subset of those elements. For example, consider the list items in the previous section selected by using "li" as our selector. The slice(start, end) method provides an easy way to reduce our list of selected elements to a specific range of indices.

We will use this method on the following markup to manipulate list items from our specified index range.

1
<ol>
2
  <li>Albania</li>
3
  <li>Austria</li>
4
  <lI>Belgium</li>
5
  <li>Bhutan</li>
6
  <li>India</li>
7
  <li>Chile</li>
8
  <li>Cyprus</li>
9
  <li>Estonia</li>
10
  <li>Gambia</li>
11
  <li>Malta</li>
12
</ol>

Here is an example that gets the list of countries from positions 5 to 8 in the previous section and adds the highlighted class to them:

1
$("ol li").slice(4, 7).addClass("highlighted");

As you can see, the indices are zero-based. The resulting markup will now look like this:

1
<ol>
2
  <li>Albania</li>
3
  <li>Austria</li>
4
  <lI>Belgium</li>
5
  <li>Bhutan</li>
6
  <li class="highlighted">India</li>
7
  <li class="highlighted">Chile</li>
8
  <li class="highlighted">Cyprus</li>
9
  <li>Estonia</li>
10
  <li>Gambia</li>
11
  <li>Malta</li>
12
</ol>

Omitting the second argument will result in the selection of all elements from the starting index until the end of the matched set.

Final Thoughts

The jQuery library was very popular a while ago, and it is still used in a lot of projects and websites. While DOM traversal and manipulation is no longer as complicated as it was in the early days, you can still use a jQuery method to write relatively less code to do something.

I won't recommend that you load jQuery to specifically use the methods discussed in this tutorial. However, using them is a good idea if you are loading the library anyway.

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.