Ways to apply CSS styling to a specific SVG element without affecting others?

Originally, I had created a single bar chart using SVG:

 bars.append("rect")
   .attr("x", midX)
   .attr("y", 0)
   .attr("width", function(d) { return x(d.values[0].value); })
   .attr("height", y.bandwidth())
   .classed("highlight", function(d) { return d.key == '15-0000'; })

This was accompanied by the following CSS styling:

rect {
   fill: #ddd;
   stroke: #000;
   stroke-width: .5px;
}

.bar rect.highlight {
   fill: #F0B27A;
   stroke: #000;
   stroke-width: .5px;
}

Later on, I added a completely different bar chart:

svg.selectAll("rect")
    .data(barchartArray)
    .enter().append("rect")
    .attr("x", -300)
    .attr("y", function(d,i) { return i*11+70})
    .attr("width", function(d,i) { return d/1000; })
    .attr("height", 10);

I am now wondering how to style this new chart in CSS without affecting the first one. For instance, how can I change the color of this chart to red without impacting the first chart? I understand that a class/id must be used, but I'm unsure of the exact formatting in CSS.

Answer №1

To style SVG elements similar to regular HTML elements, you can use classNames just like you would with normal HTML elements. Simply add a className to the root svg element.

svg.attr("class", "chart1")

Then update your CSS to target that specific class name as the parent selector.

.chart1 {
   rect {
      ...
   }
}

svg {
   height: 50px;
   width: 50px;
}

svg.bigger {
   height: 100px;
   width: 100px;
}
<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
  <circle cx="100" cy="100" r="100"/>
</svg>
<svg class="bigger" viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
  <circle cx="100" cy="100" r="100"/>
</svg>

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

Concurrent requests hitting multiple ExpressJS routes simultaneously

While configuring my routes for an expressjs app, I encountered the issue of two routes being executed when accessing a single endpoint. This is an excerpt from my code: app.get("/forgot-password", (req, res) => { .... }); app.get("/:modelName/:id ...

Exploring the depths of Cordova's capabilities: implementing a striking 3D front-to-back screen flip effect

Recently, I came across an interesting app that had a unique feature. By clicking on a button, the entire screen would flip from front to back with a 3D effect on iPhone. It was quite impressive to see in action. The developer mentioned that he achieved t ...

There was an issue loading the file list: `/Target Support Files. npx react-native run-ios`

After upgrading my Mac to macOS Ventura V13 and XCode Version 14.0.1, my React Native projects were running smoothly until today when I encountered errors while trying to start a new project. I have been searching for a solution to this problem for severa ...

Struggling with getting cards to display horizontally using React bootstrapping

I'm currently in the process of creating a portfolio website using React Bootstrapping. I'm encountering an issue where the card components I'm using to display images appear vertically instead of horizontally. I've attempted to trouble ...

Hide specific content while displaying a certain element

Creating three buttons, each of which hides all content divs and displays a specific one when clicked. For instance, clicking the second button will only show the content from the second div. function toggleContent(id) { var elements = document.getEl ...

When the inspector is open, Chrome freezes when multiple addModule() calls are made on the audioCtx

I am currently focused on developing a method to load AudioWorklet processors using OfflineAudioContext objects. My goal is to pre-generate and present visual data related to sounds that will eventually be played for the user. My approach involves utilizi ...

Refresh the custom JavaScript dropdown list without having to reload the page

I implemented this code to customize a drop-down list Selector. Is there a way to reset this code without reloading the page, maybe by triggering a function with a button click? <button onclick="reset();">Reset</button> For example, if "Jagu ...

The functionality of Jquery trigger is limited to triggering only one event that has been specified by addEventListener at a

I have decided to challenge myself by developing a library without relying on jQuery to enhance my JavaScript skills. However, I have encountered an issue while writing tests for the library where I find myself using some jQuery methods. One particular te ...

When I scroll, changing the position from fixed to absolute causes my image to jump

My goal is to implement a unique visual effect where a background image, initially positioned as "fixed", gradually moves towards the top of the webpage and then disappears as if it were absolutely positioned. However, this movement should only occur after ...

The Johnny-Five stepper initiates movement within a for-loop

I am new to using node.js and johnny-five. I want to move a stepper motor 5 times with 1000 steps each. Here is what I have tried: do 1000 Steps in cw ; console.log('ready); do 1000 steps; console.log('ready') ... It woul ...

Avoiding duplicate borders in grid layout

I'm working on a crossword puzzle design using css grid The blank cells have no color, while the other cells have a black border. The issue I'm facing is that the borders are overlapping. I've referred to similar questions on Stack Overfl ...

Using an npm package in client-side JavaScript

I've been exploring client-side GitHub packages recently and came across developers mentioning that the packages can be downloaded using npm. This confuses me as I thought these were client-side JavaScript packages. They also mentioned something about ...

invoke the modal function from a separate React file

I am currently studying react and nextjs. I am experimenting with calling a modal from another file but unfortunately it's not functioning as expected. Here is the code I used: Signin.js import { Modal } from "react-bootstrap"; import { u ...

Attempting to replicate the flipping motion of a card by applying the transform property to rotate a div element, ultimately revealing a different

I am attempting to create a series of divs that simulate the flipping action of a notecard. Unfortunately, when I hover over the div, it turns white because I have set the display property to none. I am unsure how to make the other div (.back) visible. Y ...

Having trouble entering text into a textbox in Reactjs when the state is empty

I am currently working on integrating a newsletter submit form using Reactjs/nextjs. However, I am facing an issue where once I submit the form, I am unable to type anything in the textbox. I have tried making the "state" empty but it did not resolve the ...

a:hover CSS style altering the behavior of buttons with images in a web browser

Earlier I attempted to ask this question from my phone, but it ended up being overly convoluted and confusing. Therefore, I have decided to start fresh after locating a working PC. Unfortunately, due to the sensitive nature of the project, I am unable to p ...

Updating an HTML Table with AJAX Technology

I'm struggling to figure out how to refresh an HTML table using AJAX. Since I'm not the website developer, I don't have access to the server-side information. I've been unable to find a way to reload the table on this specific page: I ...

Enable vertical overflow to adjust automatically without needing to set a specific height

I have a unique table that consists of 3 main parts: the header the content the footer Using flexbox, I managed to make the "content" section occupy all available view height. However, this was not explicitly done and now when there are too many items in ...

Migrating to Angular Universal for server-side rendering with an external API server

Thank you for taking the time to read my query. I have developed a project using server-side Node.js and client-side Angular 6. The purpose of the app is to provide information on cryptocurrency prices and details. I am now looking to transition my Angu ...

Once invoked by an ajax request, the $().ready function is executed

The functionality of this code is flawless when running on its own. However, once I make an ajax call to it, the code fails to execute. I suspect that the issue lies within $().ready, but I haven't yet identified a suitable replacement. Any suggestio ...