2026-10-09 · Q&A guide

Concatenating Variables in jQuery Selectors

Learn how to build dynamic jQuery selectors by appending variables to strings.

Why Dynamic Selectors Are Useful

When your UI contains repeating elements—cards, tabs, or form sections—IDs often include a numeric suffix. Dynamically building selectors lets you target the right element without hard‑coding each ID.

Basic String Concatenation

The most straightforward method is to use the `+` operator to join a string literal with a variable.

$('#part' + number).html(text);

Template Literals for Cleaner Syntax

ES6 template literals eliminate the need for explicit concatenation and improve readability.

$(`#part${number}`).html(text);

Common Pitfalls to Avoid

1. **Variable Scope** – Ensure the variable is defined before the selector is evaluated. 2. **Special Characters** – If the ID contains spaces or colons, escape them or use an attribute selector. 3. **Asynchronous Timing** – Place the selector inside the AJAX success callback so the element exists when you manipulate it.

Complete Working Example

Below is a minimal, functional snippet that demonstrates the concepts:

$(function() {
  $('#button').on('click', function() {
    var text = $('#text').val();
    var number = 2; // dynamic part of the ID
    $.post('ajaxskeleton.php', { red: text }, function() {
      // Use a template literal for clarity
      $(`#part${number}`).html(text);
    });
  });
});

Takeaway: Use string concatenation or template literals to dynamically build jQuery selectors, ensuring variables are defined and properly escaped.

People also ask

Can I use a variable directly inside the selector string?

No, jQuery expects a string. Concatenate or use a template literal to insert the variable.

What if my ID contains special characters?

Escape them with double backslashes or use an attribute selector, e.g., $('[id="part\:2"]').

Inspired by a public discussion on Stack Overflow. This article is an original explanation for learners.

← All posts