How to escape square brackets in jQuery selector?

To escape square brackets in jQuery selectors is quite easy. Square brackets have special meaning in CSS selectors as they're used for attribute selectors, so when they appear in element names or IDs, they need to be escaped using double backslashes (\). Let's see with an example of escaping the brackets in the name of the <select> box.

Example

In this example, we have a select element with square brackets in its name attribute. Whatever you select will get added to the textarea on button click ?

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>
        $(document).ready(function() {
            $("#addnow").click(function () {
                // Using ID selector instead of name selector with brackets
                $("#myselect :selected").each(function () {
                    $("#text").val($("#text").val() + $(this).text() + "<br>");
                });
            });
        });
    </script>
</head>
<body>
    <select name="selectemail[]" multiple="true" id="myselect">
        <option value="email">email@example.com</option>
        <option value="name">David</option>
        <option value="phone">+1-234-567-8900</option>
    </select>
    
    <textarea id="text" rows="5" cols="30"></textarea>
    <br><br>
    <button id="addnow">Select and Click to Add</button>
</body>
</html>

Escaping Square Brackets in Name Selector

If you need to select elements by their name attribute that contains square brackets, you must escape them using double backslashes ?

// Wrong way - this won't work
$("select[name='selectemail[]']")

// Correct way - escape the square brackets
$("select[name='selectemail\[\]']")

// Example usage
$(document).ready(function() {
    // Select the element with square brackets in name
    var selectElement = $("select[name='selectemail\[\]']");
    console.log("Found element:", selectElement.length);
});

Conclusion

Escaping square brackets in jQuery selectors requires using double backslashes (\[ and \]) when selecting elements by attributes containing brackets. This ensures jQuery correctly interprets the selector instead of treating brackets as CSS attribute selector syntax.

Updated on: 2026-03-13T18:16:51+05:30

591 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements