Adding CSS Classes to HTML Elements

After struggling with a question I posted yesterday about creating a "Button That When Clicked Will Display Hidden Column in HTML Table", I decided to take a different approach. Here's what I came up with:

  • I developed a button that, upon clicking, will add a new class to an element
  • This new class will allow us to toggle the visibility of a column using the 'display' property in CSS

Here's the structure of the HTML element:

echo "<td class =\"development\" id = 'tag$i'>test1</th>";
echo "<td class =\"development\" id = 'tag$i'>test2</th>";
echo "<td class =\"development\" id = 'tag$i'>test3</th>";

The variable $i represents the row number. Picture each of these <td> elements being generated within a loop to form a column.

In terms of CSS styling:

.development{
    text-align:center;
    padding-left:10px;
    display:block;
}

.hide{
    display:none;
}

Now, this is where I could use some assistance. I'm suggesting a button that, when clicked, triggers a JavaScript function to apply the '.hide' class to the <td> tags.

<button onclick="addCss()">Click me</button>

I'm uncertain about how to write the JavaScript code and whether I need to pass any parameters such as the ids for the <td> tags.

Answer №1

document.getElementById('yourId').className += ' ClassName'

//To target elements by their class name.
 document.getElementsByClassName('yourId') 

Note: the space following the first ' is crucial when appending a class name.

Why? : When you have a class named "class1" and add "class2" - It will become "class1class2"

By including the space, it will appear as "class1 class2" and be treated as two distinct classes.

<button onclick="document.getElementById('yourId').className += ' ClassName';">Click me</button>

If you wish to create a more effective solution.

<script>

function addCss(element) {   
document.getElementById(element).className += ' ClassName'; 
}

</script>

Simply invoke the function as initially done. You can even specify the class name as a parameter.

Answer №2

When you need to replace a class, use this code:

document.getElementById("id").className = "newclass";

If you want to add a new class, you can do so with this code:
document.getElementById("id").className += " anotherclass";

function addCss(){
document.getElementById("b").className = "hide"; 
}

function newCss(){
document.getElementById("b").className = "show"; 
}
body {
  font-size: 3em;
  background: honeydew;
}

.hide {
  display: none;  
}

.show {
  display: table-cell;  
}
<table>
<tr>
<td id=a style="background:skyblue">A</td>
<td id=b style="background:yellowgreen">B</td>
<td id=c style="background:gold">C</td> 
<td id=d style="background:orangered">D</td>
</tr>
</table>

<button onclick="addCss()">hide B cell</button>
<button onclick="newCss()">show B cell</button>

Answer №3

With the power of jQuery, one can seamlessly incorporate this snippet into the addCss function:

$('td').addClass('hide');

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

Get a collection of stock statistics and quotes using Flutter and the IEX JSON API

IEX JSON API Integration: import 'package:http/http.dart' as http; import 'dart:convert'; import '../models/stocks.dart'; Future<Map<String,dynamic>> getStocksData() async { const url = 'https:/ ...

Optimal method for identifying all inputs resembling text

I'm in the process of implementing keyboard shortcuts on a webpage, but I seem to be encountering a persistent bug. It is essential that keyboard shortcuts do not get activated while the user is typing in a text-like input field. The approach for hand ...

Creating a three-dimensional network visualization in three.js

I'm currently working on creating a 3D graph using three.js Code: <html> <head> <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1b7f6369747441567877746c79 ...

Customize footer's background color based on current route in Angular

My footer has a unique wavy design that functions as a block, but I'm facing an issue where the transparent part of the wave appears white because it's taking up space as a block. 1 2 3 Below is the CSS code being used: .wave{ background: ...

The HTML element cannot be set within page.evaluate in Node.js Puppeteer

I've run into an issue while using node.js puppeteer, specifically with the page.evaluate method. I'm experiencing difficulties with this part of my code: console.log(response); //This line is valid as it prints a regular string awa ...

Issue with displaying info window when clicking on marker in react-google-maps

Seeking assistance in opening the info window of specific markers when clicked. All markers and map are displaying correctly, with correct titles appearing on hover. However, clicking a marker does not trigger the info window to show. The console confirms ...

Uploading CouchDB document attachments using an HTML form and jQuery functionality

I am currently in the process of developing a web form that, upon submission, will generate a couchdb document and attach file(s) to it. I have followed tutorials and visited forums that suggest a two-stage process similar to futon's approach. While I ...

Glitches of white light during loading screens on your Prestashop website

There's a strange occurrence on the website where it flashes white DURING (not just at the start) every time a page loads. Initially, the page seems to load smoothly and almost completely, but then there is a sudden flash before all elements are disp ...

The orbitController in threejs is malfunctioning and failing to properly adjust the camera's LookAt

Currently, I am working on a project using three.js. In this project, I have implemented OrbitControls for my camera. However, there are situations where I need to manually adjust the rotation of the camera. The challenge I am facing is that when I try t ...

Conceal an extended menu by clicking away from the container: a guide on implementing a code snippet

I'm working on a menu that opens a sub-menu section when clicked (let's call this container: "sub-menu"). I want the "sub-menu" to disappear if the user clicks outside of it, on the rest of the page. I found a solution on How do I detect a click ...

Dynamic menu plugin for JQuery

I am still new to jQuery and currently learning how to efficiently use it in website development. I am currently working on implementing a responsive navigation plugin that I came across online. However, I have encountered an issue with the plugin where th ...

Exploring Firebase database with AngularJS to iterate through an array of objects

I'm working on an app that pulls data from a Firebase database, but I'm running into an issue. When I try to loop through the data and display it on the page, nothing shows up. However, if I use console.log to output the data, it's all there ...

Unique Selector Customization

Is there a way to style all custom elements in CSS? I am looking to make custom elements default to block display (as most browsers render them inline by default) and then adjust as needed. A potential rule I have in mind is: *::custom { display: blo ...

Characteristics Exclusive to Inner Division

Currently, I am working on creating an arrow-like element that moves up when hovered over and returns to its original position when the mouse is no longer hovering. To achieve this effect, I have placed the arrow within a parent div and set up event listen ...

I can't figure out why I'm receiving undefined even though all the variables are populated with the necessary

I have been working on a project that involves implementing email and password authentication using Firebase. However, I encountered an error when the user submits their credentials: FirebaseError: Firebase: Error (auth/admin-restricted-operation). at ...

Unlock the ability to retrieve the context element from a dynamically bound event within the event handler using jQuery

I have a chunk of HTML that gets inserted into the page and is connected to a click event handler. Here's an example in the code snippet below: var matchMore = $(".match-more-btn"); matchList.on("click", matchMore, function() { var self = $(this); ...

Change this time record into a standard date

"usage_timestamp": [13308678945000000] I am trying to convert this unique timestamp format found in my JSON file into a normal date using Node.js. Can anyone help me with the proper conversion process? It seems like this is not your typical Uni ...

What is the best way to update the old string values with the new string values?

function decipher(str) { // YOU DID IT! var newString = str.split(" "); for(var x = 0; x < newString.length; x++ ){ for( var y = 0; y < newString[x].length; y++ ){ if(newString[x].charCodeAt(y) < 78){ String.fromCharCode(ne ...

Having multiple instances of jQuery running concurrently on a single webpage

I am a novice when it comes to jQuery and I'm facing some issues with it. I have a basic slideshow and a weather plugin that I would like to incorporate, but strangely they both seem to malfunction when used together. <script src="js/jquery.js"> ...

Issue with applying Angular animation to child element

Here I have set up two different animations. animations: [ trigger('fadeIn', [ transition('void => *', [ style({opacity: 0}), animate(500), ]), ]), trigger('fallIn',[ transition ...