Attempting to assign a new class to a <div> using JavaScript

I'm facing an issue where I need to add a class to a div without replacing the existing classes. Despite my code being correct, it doesn't seem to work as expected.

function clickTab(clicked_id) {
  var x = clicked_id
  x.className += " active"
}
.active {
  background-color:red;
}
<div id="communitytab" onClick="clickTab(this.id)">Interesting community content</div>

Answer №1

Passing the element's ID is not enough, you also need to read the element.

Here is a suggestion:

function activateTab(clicked_id) {
    var x = document.getElementById(clicked_id);
    x.className += " active"
}

Answer №2

It turns out that the issue was simply with the targeting, and this solution will successfully function with any element that triggers the specific function.

function selectTab(selected_id) {
    var x = selected_id.id;
    document.getElementById(x).classList.add("active");
}
.active {
  background-color: blue;
}
<div id="communitytab" onClick="clickTab(this)">Fascinating community content</div>

Answer №3

To simplify the process, it's best to pass the entire element instead of just the ID to the function. This way, you can directly access the element's ID without needing to query the DOM again:

function clickTab(el) {
  el.className = " active";
  
  // Retrieve the ID
  var id = el.id;
  console.log(id);
}
.active {
  background-color:red;
}
<div id="communitytab" onClick="clickTab(this)">Interesting community content</div>

It's important to avoid using inline JS. Instead, utilize Element.addEventListener which will pass the DOM node as this. Additionally, make use of classList instead of className as it is widely supported (~98% of browser traffic), allowing you to easily manipulate classes with methods like el.classList.add('active'):

function clickTab() {
  var el = this;
  el.classList.add('active');
  
  // Retrieve the ID
  var id = el.id;
  console.log(id);
}

document.getElementById('communitytab').addEventListener('click', clickTab);
.active {
  background-color:red;
}
<div id="communitytab">Interesting community content</div>

Answer №4

Upon further examination, it seems that your code functions properly when executed by a browser engine, but encounters issues in jsfiddle.

Interestingly, there is a related discussion on this topic here: JavaScript not running on jsfiddle.net

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

Obtain an identifier to be used as dynamic data in an ajax request with jQuery

I am struggling to extract the id from links that trigger the same ajax function. I have over 30 links generated dynamically, as shown below: <a href="javascript:void(0)" id="105">Item 105</a> <a href="javascript:void(0)" id="379">Item 3 ...

What is the best way to make a line widget that has rounded edges at both the beginning and end?

I've been scouring the internet for a solution to this problem, but so far I haven't had any luck. My goal is to design a horizontal line with dots at each end, similar to this example. Does anyone know how I can achieve this using CSS? I atte ...

Troubleshooting issue with jest expect.any() failing to work with a custom class following migration from JavaScript to TypeScript

I recently made the switch to TypeScript in my project, and now some of my Jest tests are failing. It appears that the next function below is no longer being called with an AppError object, but with an Error object instead. Previously, the assertion expec ...

AngularJS is experiencing an issue where the dynamic partial stored in $templateCache is being removed

It seems like my code is haunted or I've made a mistake: Here is the structure of a json feed I'm working with: { "sections": [ { "identifier": "header", "blocks": [ { "identifier": "onebyone", "htm ...

Dynamic horizontal scrolling

I need help implementing a site using React that scrolls horizontally. I'm unsure how to implement certain aspects, so I am looking for some assistance. Within a wrapper, I have multiple container Divs. <div class="wrapper"> <div class=" ...

Creating a user-friendly form in a Nuxt/Vue application that enables dynamic attribute creation

I am currently working on designing a form that enables users to create different variations for a product within a Nuxt/Vue application. The goal is to provide users with the ability to specify attributes for each variation using a text field. These attr ...

Real-time data updates not working in jQuery data table

I am currently dealing with a data table and using ajax to fetch data for display on my HTML DOM page. However, I have encountered an issue after implementing server-side processing for the data table. Even though I can successfully retrieve records in my ...

Locate an original identifier using Selenium WebDriver

In search of a distinctive identifier for the "update profile picture button" on my Facebook account to utilize it in automation testing with Selenium WebDriver and Java. I attempted driver.findElement(By.className("_156p")).click();, but unfortunately, i ...

What is the best way to find the average time in Typescript?

I am dealing with an object that contains the following properties: numberOfReturns: number = 0; returns_explanations: string [] = []; departure_time: string = ''; arrival_time: string = ''; The departure_time property hold ...

Managing Input Type Dropdown Selections Using Jquery

I am currently in the process of developing a website. On this website, there is a form that includes 3 dropdown menus as shown below. I would like to implement a feature where selecting the number 5 from the Adults menu will automatically display 5 in the ...

Sequentially transferring data to users and processing in Node.js

I am currently working on a website using node.js with express and socket.io. The server is set up to send photos and data from every file in a directory to the user using the socket.emit function. However, I have encountered an issue with the code where ...

Karma jasmine and an angular controller that utilizes the 'Controller as' syntax (where 'this' is used instead of $scope)

I'm having trouble setting up karma for my unit tests, specifically on a basic example: Here is the controller file: angular.module('balrogApp.requests', [ /* Dependencies */ ]) // Routes configuration .config(['$routeProvider&a ...

Error Message: The function "menu" is not a valid function

I've encountered an issue with a function not being called properly. The error message states "TypeError: menu is not a function." I attempted to troubleshoot by moving the function before the HTML that calls it, but unfortunately, this did not resolv ...

What is the reason for the difference in width between Bootstrap-5 row and regular div blocks?

My code may seem simple, but I have encountered an issue with it: <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="99fbf6f6edeaedebf8e9d9acb7abb7a9">[email protected]</a ...

Align watermark content to the far left side

Having trouble getting my watermark to align properly on the left side of my website's main content. Here is how it currently looks: https://i.sstatic.net/Nfhh5.png The issue arises when I resize the screen or switch to mobile view, as the watermark ...

"Exploring the magic of product galleries: A behind-the-scenes look at how websites create images

Have you ever wondered how this website creates the customization effect in its gallery? When you adjust the color, stones, or other attributes of the ring, it appears as though a new image is being generated. (click Customize) Do you believe they have a ...

Incorporate a new JavaScript animation as the background for an established website, replacing the static background image

Seeking assistance with my portfolio as I delve into the world of Webdesign and learn the basics from templates. How can I integrate this javascript code into the background of my site, replacing the current minecraft image? Every attempt to implement it ...

Tips for creating animations with JavaScript on a webpage

I created a navigation bar for practice and attempted to show or hide its content only when its title is clicked. I successfully toggled a hidden class on and off, but I also wanted it to transition and slide down instead of just appearing suddenly. Unfort ...

How come when I click on the edit button, the selected data's model doesn't appear in the dropdown menu as I would like it to?

this is the function in my controller public function getModel($make_id = null) { $make_id = request()->make_id; $carsmodel = CarModel::where('make_id', $make_id)->orderBy('model', 'ASC')->get(); return re ...

What is the best way to transfer a row value from one table to another and then reinsert it back into the original table

I attempted to transfer a row value from one table to another and then back to the original table, but unfortunately, I was unable to find a solution. $('#one tbody tr td input.checkbox').click(function() { if ($(this).attr('checked&apo ...