Home > Web Front-end > JS Tutorial > body text

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

Linda Hamilton
Release: 2024-10-23 07:42:02
Original
250 people have browsed it

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);
    });
  });
});
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!