What is the escapeSelector() method in jQuery?

Overview

The escapeSelector() method is a built-in method in jQuery, and is used to escape CSS meta-characters.

jQuery uses some sort of selector for selecting DOM elements. If any selector contains special characters like # or ., then to use such a selector we need to use the escapeSelector() method.

Syntax

$.escapeSelector(selector);

Parameters

This method accepts the following parameters:

  • selector: This is the selector that needs to be escaped.

Example

Let’s look at an example of the escapeSelector() method in the code snippet below:

Example of escapeSelector() method

Explanation

In the HTML tab:

  • Line 5: We create a div content.
  • Lines 6 to 10: We create five p elements.

Note: We add the .line class to every alternative p.

  • Line 12: We create a button Highlight.
  • Line 14: We import the jQuery script.

In the JavaScript tab:

  • Line 3: We attach the click() method on the Highlight button.
  • Line 5: We use the escapeSelector() method to select all the elements with class .line. Also, we use the toggleClass() method to toggle class highlight.

Output

  • When the Highlight button is clicked, the escapeSelector() method escapes the selector .line and all the elements with this selector are selected.
  • The background color of those selected items is toggled.

Free Resources