The problem with Jquery's Id selector when compared to the Js Id selector

I created a simple program to showcase the issue I'm currently facing.

  • Essentially, in this program, I input a name and a color which are then added to an unordered list when the submit button is clicked.
  • Afterwards, I attempted to change the color of the sentence using a jQuery id selector, but the color doesn't update. However, using getElementById works correctly.
  • For example, if I input "Tom" as the name and "red" as the color, a red sentence should be displayed.

Here is the version using a jQuery selector:

$(document).ready(function () {
// initialization
$('select').formSelect();

$('#myForm').submit(function (e) {
let name = $('#name').val();
let color = $('#color').val();
addToList(name,color);
e.preventDefault();
});
});

function addToList (n,c) {
$('#main').append(`<li id=${n}**${c}>My name is ${n}. My favorite color is: ${c}</li>`);
$(`#${n}**${c}`).css({'color':`${c}`});
// document.getElementById(`${n}**${c}`).style.color = c;
}
<!DOCTYPE html>
<html>
<head>
  <!--Import Google Icon Font-->
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <!-- Compiled and minified CSS -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/css/materialize.min.css">
  <!--Let browser know website is optimized for mobile-->
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />

  <title>My Lab</title>
</head>
  <body>

<div class="container">
 <form id="myForm">
 <div class="input-field">
  <label for="name">Name</label>
  <input type="text" id="name" required>
  </div>
  <div class="input-field">
  <label for="color">Color</label>
  <input type="text" id="color" required>
  <button class="btn" type="submit">Submit</button>
 </div>
 <ul id="main"></ul>
 </form>
</div>


  </body>
<!--Import jQuery before materialize.js-->
 <script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/js/materialize.min.js"></script>
 <script src="app.js"></script>
 </html>

Below is how I utilized getElementById, where it works successfully:

$(document).ready(function () {
// initialization
$('select').formSelect();

$('#myForm').submit(function (e) {
let name = $('#name').val();
let color = $('#color').val();
addToList(name,color);
e.preventDefault();
});
});

function addToList (n,c) {
$('#main').append(`<li id=${n}**${c}>My name is ${n}. My favorite color is: ${c}</li>`);
// $(`#${n}**${c}`).css({'color':`${c}`});
document.getElementById(`${n}**${c}`).style.color = c;
}
<!DOCTYPE html>
<html>
<head>
  <!--Import Google Icon Font-->
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <!-- Compiled and minified CSS -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/css/materialize.min.css">
  <!--Let browser know website is optimized for mobile-->
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />

  <title>My Lab</title>
</head>
  <body>

<div class="container">
 <form id="myForm">
 <div class="input-field">
  <label for="name">Name</label>
  <input type="text" id="name" required>
  </div>
  <div class="input-field">
  <label for="color">Color</label>
  <input type="text" id="color" required>
  <button class="btn" type="submit">Submit</button>
 </div>
 <ul id="main"></ul>
 </form>
</div>


  </body>
<!--Import jQuery before materialize.js-->
 <script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/js/materialize.min.js"></script>
 <script src="app.js"></script>
 </html>

Answer №1

* within a selector holds a specific significance. It is necessary to properly escape it using $.escapeSelector(). Instead of this:

$(`#${n}**${c}`).css({'color':`${c}`});

you should use this:

$(`#${$.escapeSelector(`${n}**${c}`)}`).css({'color':`${c}`});

View the Working Demo:

$(document).ready(function() {
  // code for initialization
  $('select').formSelect();

  $('#myForm').submit(function(e) {
    let name = $('#name').val();
    let color = $('#color').val();
    addToList(name, color);
    e.preventDefault();
  });
});

function addToList(n, c) {
  // adding elements to list
  $('#main').append(`<li id=${n}**${c}>My name is ${n}. My favorite color is: ${c}</li>`);
  $(`#${$.escapeSelector(`${n}**${c}`)}`).css({
    'color': `${c}`
  });
}
<!--Import Google Icon Font-->
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <!-- Compiled and minified CSS -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/css/materialize.min.css">
  <!--Let browser know website is optimized for mobile-->
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />

  <title>My Lab</title>
</head>

<body>

  <div class="container">
    <form id="myForm">
      <div class="input-field">
        <label for="name">Name</label>
        <input type="text" id="name" required>
      </div>
      <div class="input-field">
        <label for="color">Color</label>
        <input type="text" id="color" required>
        <button class="btn" type="submit">Submit</button>
      </div>
      <ul id="main"></ul>
    </form>
  </div>


<!--Import jQuery before materialize.js-->
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/js/materialize.min.js"></script>
<script src="app.js"></script>

Answer №2

Your id is acceptable as an HTML id, but it is not suitable for use as a CSS ID selector (Reference here). Ideally, refrain from utilizing user input to create your element IDs.

If you wish to utilize jQuery while keeping that particular ID format, you have a couple of options:

  • Retrieve the element by its ID using getElementById and then apply $():

    $(document.getElementById(`${n}**${c}`)).css({'color':`${c}`});
    

    or

  • Alternatively, opt for an attribute selector:

    $(`[id="${n}**${c}:]`)).css({'color':`${c}`});`, 
    

Just a quick note: Instead of .css({'color':${c}}), you may also write .css('color',${c}) if you prefer.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What alternative can be used for jquery isotope when JavaScript is not enabled?

Is there a backup plan for jQuery isotope if JavaScript isn't working? For instance, if I'm using the fitColumns feature, is there an alternative layout style available in case JavaScript is disabled, similar to what is seen on the new Myspace? ...

Incorporate a CSS style sheet into the app_offline file

It's been a challenge for me to create a custom app_offline.htm page and include links to my css files in the project. Unfortunately, the code snippet below doesn't seem to be working as expected: <link href="/Content/Themes/screen.css" rel=" ...

Having difficulty creating a basic container

As a beginner in web development using html/css, I am eager to learn and create something simple. I want to design a responsive fixed box that always maintains a 20px distance from the viewport edges. The idea is that as the screen size changes, the box ...

Ways to establish the gradient

Here is the code snippet I am currently working with. .imgcol1 { background-image: url(https://picsum.photos/200/300); background-repeat: no-repeat; background-size: cover; height: 190px; width: 520px; } .col1 { margin: 75px; } .grad { b ...

Enhance the user experience by incorporating a tooltip into the input field using Bootstrap 5

I have implemented custom CSS to display an error icon with a tooltip, but after upgrading to Bootstrap 5, I am unable to achieve the same result. Expected: https://i.sstatic.net/Mjvik.png .icon { position: absolute; bottom: 6px; right: 10.5px; ...

Use jQuery to send a variable value to a MySQL database by making a POST

Utilizing ajax/json, I fetch a random row from a mysql-server using PHP. The different data obtained from the random row is stored in variables. $.ajax({ url: 'api.php', data: "", ...

Seeking assistance with images for a website

I'm currently working on a school project where we are creating a website. However, I've encountered an issue with an image. It's a bit difficult to explain, so I've uploaded a video to help illustrate the problem. Essentially, I want t ...

How can I automatically disable the button after resetting the form's state?

This form has a feature where the submit button is disabled until all form fields are complete. Once the submit button is clicked, preventDefault() function runs and an alert pops up. However, after closing the alert, the form resets but the button state r ...

HTML formatter in VS Code that maintains inline comments intact

Currently on the hunt for a reliable HTML formatter plugin for VS Code that won't mess up existing HTML code with inline comments like this: <div>hello</div><!-- class="world" --> Don't want it to end up like this: <div> ...

What could be causing the unusually large value returned by my array.length?

When I push JSON objects to my "list" array, the issue arises when I try to retrieve its length. Instead of getting the number of items in the array, it seems like I am getting the count of characters. UPDATE: Refer to the answers for a solution. The prob ...

Position image to the right within the anchor

Could anyone assist me in aligning my image within the <a> Tag to the right? The text should be set to float: left and the image should have float: right. Additionally, the image should be vertically centered. I'm struggling to figure this out o ...

Streamlining the process of formatting URLs?

I was pondering if there is a more efficient method to accomplish this task. I extract links from a webpage, but many of them are relative. for example /index.html for instance /home.index.html Currently, my approach involves adding the home URL to compe ...

Searching for specific data within an HTML table using multiple attributes in JQuery

I need to search for rows based on three attributes in each row. Currently, I am able to search by one attribute using the following code: var rows = $("#tbl1 > tbody > tr[cName=1]"); However, I encounter an error when trying to search by all thre ...

Issue with Submit Button Functionality in Django Form Submission

I'm currently facing an issue with an HTML template I built using Bootstrap. My problem lies in the fact that I have a JavaScript function that dynamically adds rows to a Django form with specific fields whenever I need to. However, when I add a row, ...

Is it possible for me to automatically add a line break following every image that is fetched from the Flickr API?

Hello there! I'm facing a little challenge with inserting a line break after each image that loads from the Flickr API. It's tricky to manipulate the style of data that hasn't loaded in the browser yet. I've experimented with using the ...

What could be causing my col-x to not function correctly in Bootstrap?

I am trying to modify my Bootstrap navbar by adding a Login button, but I encountered an issue. When I use col-x classes inside the navbar to separate elements equally, they only cover 50% of the width and no more. However, using col-x classes outside the ...

Issue with HTML file not found in Python Tornado AngularJS application (using ui-router)

Looking at my code Folder Structure: App- |--- static | |--- css | |--- js | |--- app.js | |--- templates | | --- header.html | | --- template.html | | --- footer.html | | --- index.html |--- startup ...

Unable to trigger onSelect event on the datepicker component

Whenever a date is chosen, I need to trigger a javascript function. Here is the javascript code: $(document).ready(function(){ var date_input=$('input[name="date"]'); //our date input has the name "date" var container=$('.bootstrap- ...

Managing task durations within the asp.net framework

When designing an online examination system, one challenge is how to manage the elapsed and remaining time for each exam. Initially, I addressed this issue by utilizing JavaScript to create a client-side timer on the exam webpage as soon as the student e ...

Try using the statement "Assert.IsTrue" to confirm the object's position

Objective: By pressing on a custom link, you are directed to a webpage where the screen displays specific text - "Padding - Shorthand Property". The aim is to use Assert.IsTrue to ensure that the padding shorthand property and its content are within the ...