`The functionalities of classList.add and classList.remove aren't behaving as anticipated.`

I'm currently working on a list of items (ul, li) that have a class applied to them which adds a left border and bold highlight when clicked.

My goal is to reset the style of the previously clicked item back to its original state when a new item is clicked, and then apply the new style to the currently active item.

What's puzzling is that even though the DOM inspection shows that the previous items still have the altered class, the console output indicates otherwise.

 function myFunctionTest(id_word) {
  var items = document.getElementsByClassName("process-itemz");
         for (var i = items.length - 1; i >= 0; --i) {
         items[i].classList.remove("test123");
}

var element = document.getElementById(id_word);
  element.classList.add("test123");

}

For a live demonstration, check out this fiddle: https://jsfiddle.net/y5kwmu6j/

Answer №1

There are two key points to consider:

element.classList.add = "test123";
needs to be corrected to
element.classList.add("test123");

It is advisable to rearrange the order of the css rules so that the .test123 rules appear after the .process-itemz rules. Both rules have the same level of specificity, therefore the latter ones will take precedence.

Answer №2

After making a few syntax changes and reformatting your loop, the code snippet provided should work perfectly fine. Just make sure that your JavaScript is properly linked in your HTML file or embedded between script tags.

Here's the modified code snippet for your reference:

function myFunctionTest(id_word) {
  alert(1);
  var items = document.getElementsByClassName("process-itemz");
  for (var i = 0; i < items.length - 1; i++) {
    items[i].classList.remove("test123");
  }

  var element = document.getElementById(id_word);
  element.classList.add("test123");
}
.default {
  font-weight: 200;
}

.test123 {
  border-left: 1rem solid rgba(167, 194, 15, 0.623);
  font-weight: bold;
}

.process-itemz {
  border-left: 1rem solid rgba(167, 194, 15, 0);
  font-weight: inherit;
}

Make sure to include the following HTML code snippet along with the JavaScript:

<div class="default">
  <ul id="foo">
    <li>
      <span onclick="myFunctionTest(this.id)" id="testa123" class="process-itemz">&ThickSpace;&ThickSpace;&ThickSpace;&ThickSpace;Excavation Hire</span>
    </li>
    <li>
      <span onclick="myFunctionTest(this.id)" id="testb123" class="process-itemz">&ThickSpace;&ThickSpace;&ThickSpace;&ThickSpace; Rubbish Removal</span>
    </li>
  </ul>
</div>

Answer №3

If you're looking to make your CSS selectors more specific, one way to do it is by combining class selectors. Instead of having separate classes like .process-items and .test123, you can combine them into one selector like .process-itemz.test123. This will ensure that the specificity of the selector is always higher, regardless of the order of the selectors in your CSS.

For more information on how specificity is calculated in CSS, you can check out the MDN article on the topic: See "How is specificity calculated?" on MDN

Keep in mind that the effectiveness of this approach may vary depending on your specific use case.

function myFunctionTest(id_word) {
  var items = document.getElementsByClassName("process-itemz");
  for (var i = items.length - 1; i >= 0; --i) {
    items[i].classList.remove("test123");
  }

  var element = document.getElementById(id_word);
  element.classList.add("test123");
}
.default {
  font-weight: 200;
}

.process-itemz {
  border-left: 1rem solid rgba(167, 194, 15, 0);
  font-weight: inherit;
}

.process-itemz.test123 {
  border-left: 1rem solid rgba(167, 194, 15, 0.623);
  font-weight: bold;
}
<div class="default">
  <ul id="foo">
    <li>

      <span onclick="myFunctionTest(this.id);" id="testa123" class="process-itemz">&ThickSpace;&ThickSpace;&ThickSpace;&ThickSpace;
                   Excavation Hire
                  </span>
    </li>
    <li>


      <span onclick="myFunctionTest(this.id);" id="testb123" class="process-itemz">&ThickSpace;&ThickSpace;&ThickSpace;&ThickSpace; Rubbish Removal</span>
    </li>
  </ul>
</div>

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

Using Typescript to pass a property as one of the keys in an object's list of values

In my React Native project, I need to pass a string value from one component to another. The different options for the value can be found in the ScannerAction object: export const ScannerAction = { move: 'move', inventory: 'inventory&apo ...

Constructing Browserify with dependencies containing require statements within a try-catch block

When attempting to integrate timbre.js (npm version) with Browserify, I encountered an issue where require statements for optional dependencies were enclosed in a try statement (check the source here). This resulted in a browserify build error displaying: ...

Using input masking to restrict user input to only numbers and English alphabet characters

My input field is masked as "999999999" and functions correctly with an English keyboard. However, I am able to enter Japanese/Chinese characters into it, which breaks the masking. Is there a way to limit input to English keyboard numerics only? <inpu ...

Designing templates for websites and applications using node.js

Simplified Question: As I delve into improving my skills with node.js, I'm exploring the concept of templating. How would using node to serve one HTML file and loading page-specific information through AJAX/sockets impact performance and design princ ...

Expanding sidebar height to match parent using Flexbox

Looking for the best way to adjust a child element to match the height of its parent? I've experimented with various techniques, but haven't had much success. I'm leaning towards using flexbox as it seems to be the latest trend. Here's ...

Exploring data elements in a Javascript array

Is there a way to use Javascript or jQuery to address the individual employee number, tasks, and sites in the following JSON array? $.each(mySchedule, function(i, obj) { console.log(obj.employees); }); var mySchedule = { "schedule": { "empl ...

Mobile devices not showing the Navbar bootstrap menu

My header.php works perfectly on desktop, but the navigation bar is not displaying properly on mobile devices. Here is my code: <!DOCTYPE html> <html> <head> <title>International Pvt. Ltd.</title> <meta name="viewpo ...

Prevent the browser from autofilling password information in a React Material UI textfield when it is in focus

I am currently utilizing React Material UI 4 and I am looking to disable the browser autofill/auto complete suggestion when focusing on my password field generated from `TextField`. Although it works for username and email, I am encountering issues with d ...

What purpose does tagging serve in my template for polymer property binding?

I'm currently exploring the way Polymer handles the rendering of properties in a custom element's template. I've come across some interesting behavior that I haven't been able to fully grasp yet. Specifically, I noticed that certain pro ...

Utilizing Template Styling for Iterating through Lists in Vue.js

I would like the output format to display one player value followed by one monster value, repeating this pattern for each pair of values. new Vue({ el: app, data: { output: { player: [1, 5, 61, 98, 15, 315, 154, 65], monster: [2,14, ...

Poor mapping on Google Maps API

I've been trying to embed a Google Maps on my website, but for some reason, it keeps stretching and showing grey sections with rounded borders. Here's the code I'm using: <div class="p-5 col-6 d-flex flex-column justify-content-between"& ...

A capability that operates on an array of pairs as its parameter, where the primary component of each pair signifies the superior category of the secondary

I'm grappling with developing a TypeScript function that takes an array of Tuples as input. Each tuple should consist of two elements, where the first element acts as a parent type to the second element - essentially, the second element must extend th ...

Leverage the AJAX Search Lite Plugin within the top navigation of your WordPress website's header file

I am interested in utilizing the "AJAX Search Lite 3.0.6" plugin within my WordPress Theme. Plugin Link After implementing the shortcode, I noticed that it was not appearing on the navigation bar as expected: <body> <!-- Header --> & ...

Efficient method for deleting a specific item from a JSON object in React.js

Within the REACT JS framework, I am managing a JSON object in the state component "myrecords". The items within this object are organized by their respective Company Names and have the following structure: { "Master Automotives": [ { ...

Exploring JSON data with multiple nested layers of iteration

I'm currently working on a project that involves parsing through a JSON file with a complex structure. I've been attempting to extract a link to an image within the JSON data, but my current approach is resulting in an error. Below you'll fi ...

"Trouble with getting the Twitter Bootstrap dropdown menu to function properly

Currently, I am facing a challenge with my project as the dropdowns on the menu are not functioning properly. Despite having all the necessary files included, it seems like there might be an issue within my code. You can view the page here: (please try t ...

"Navigation Side Menu: w3-sidebar with hamburger toggle feature

If you are looking to implement the w3-sidebar, you can find it here: https://www.w3schools.com/w3css/tryit.asp?filename=tryw3css_sidebar_over The existing code uses a "hanburger" icon to open the side menu and a "Close X" menu item to close it. To simpl ...

Refreshing specific iframes without having to reload the entire webpage using jQuery

As the page loads initially, a hidden iframe and other visible ones are present. When a button is clicked, one of the visible iframes needs to be hidden while another becomes visible (with its src attribute set accordingly). The goal is to achieve this wit ...

Using both italic and regular text in an HTML (or ASP.NET) textbox can add emphasis and enhance readability for

Is there a way to achieve this using JavaScript? For instance, if the initial text is 'Axxxxxx', I want it to be displayed in a textbox with normal style for the first letter and italic style for the rest like 'A*xxxxxx*' If the initia ...

Async Autocomplete fails to display options if the label keys do not match the filtering keys

While I have experience with ReactJs and Material UI, I encountered a surprising issue. I am using the Material-UI Autocomplete component as shown below. The users variable is an array of objects. When searching for firstName or lastName in the user table, ...