Home  >  Article  >  Web Front-end  >  How to Select HTML Elements with Periods in their ID Using jQuery?

How to Select HTML Elements with Periods in their ID Using jQuery?

Linda Hamilton
Linda HamiltonOriginal
2024-10-23 07:42:02251browse

How to Select HTML Elements with Periods in their ID Using jQuery?

Selecting Elements with Periods in Their ID Using jQuery

Problem:

When using jQuery to select an element with a period (.) in its ID, the provided selectors do not match due to character escaping conflicts between JavaScript and jQuery.

Fix:

To resolve this issue, you must escape the period character using two backslashes before each one within the jQuery selector. This is because:

  • A backslash in a jQuery selector escapes the next character.
  • The first backslash is needed to escape the second backslash, allowing the second one to escape the period character.

Solution:

$(function() {
  $.getJSON("/Location/GetCountryList", null, function(data) {
    $("#Address\.Country").fillSelect(data);
  });
  $("#Address\.Country").change(function() {
    $.getJSON("/Location/GetRegionsForCountry", { country: $(this).val() }, function(data) {
      $("#Address\.State").fillSelect(data);
    });
  });
});

Explanation:

In the modified code, double backslashes escape the periods in the "Address.Country" and "Address.State" selectors, allowing jQuery to correctly find and interact with these elements.

Reference:

For more information, refer to the jQuery FAQ: How do I select an element by an ID that has characters used in CSS notation?

The above is the detailed content of How to Select HTML Elements with Periods in their ID Using jQuery?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn