How do you go about adjusting the color of an SVG's path?

Update: I've noticed that there are similar questions on SO, but unfortunately the solutions provided didn't work for me.

My goal is to change the color of SVG paths directly, not just an inner color but the path itself.

I initially attempted to do so with CSS, but it had no effect. Then I tried using JavaScript, which almost worked:

Currently, when the image is loaded, it's displayed in black by default.

<object id = 'test' data="images/icons/040__file_delete.svg" type="image/svg+xml"></object>

What I want to achieve is changing the color to green.

    <script>
        $(function(){
            document.getElementById("test").addEventListener("load", function() {
                var doc = this.getSVGDocument();
                console.log(doc);//works fine
                var p = doc.querySelector("path"); //works
                p.setAttribute("stroke", "green");
            });    
        })
    </script>

The above approach does result in a color change, but it also adds a border to the path. I have also tried using properties like "color," "fillcolor," and "fill" without success.

Update II: Here is the source code of the SVG:

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.0" id="图层_1" x="0px" y="0px" viewBox="0 0 18 18" style="enable-background:new 0 0 18 18;" xml:space="preserve">
<style type="text/css">
    .st0{fill:#231815;}
</style>
<g>
    <g>
        <g>
            <g>
                <g>
                    <path class="st0" d="M13,17.5H5c-1.4,0-2.5-1.1-2.5-2.5V3c0-1.4,1.1-2.5,2.5-2.5h3.6c0.4,0,0.8,0.2,1.1,0.4l5.4,5.4       c0.3,0.3,0.4,0.7,0.4,1.1V15C15.5,16.4,14.4,17.5,13,17.5z M5,1.5C4.2,1.5,3.5,2.2,3.5,3v12c0,0.8,0.7,1.5,1.5,1.5h8       c0.8,0,1.5-0.7,1.5-1.5V7.4c0-0.1-0.1-0.3-0.1-0.4L8.9,1.6C8.8,1.6,8.7,1.5,8.6,1.5H5z" fill="green"/>
                </g>
                <g>
                    <path class="st0" d="M15,7.5h-4C9.6,7.5,8.5,6.4,8.5,5V1c0-0.3,0.2-0.5,0.5-0.5S9.5,0.7,9.5,1v4c0,0.8,0.7,1.5,1.5,1.5h4       c0.3,0,0.5,0.2,0.5,0.5S15.3,7.5,15,7.5z"/>
                </g>
            </g>
            <g>
                <g>
                    <path class="st0" d="M10.5,13.9c-0.1,0-0.3,0-0.4-0.1l-3-3C7,10.5,7,10.2,7.1,10s0.5-0.2,0.7,0l3,3c0.2,0.2,0.2,0.5,0,0.7       C10.8,13.8,10.6,13.9,10.5,13.9z"/>
                </g>
                <g>
                    <path class="st0" d="M7.5,13.9c-0.1,0-0.3,0-0.4-0.1C7,13.5,7,13.2,7.1,13l3-3c0.2-0.2,0.5-0.2,0.7,0s0.2,0.5,0,0.7l-3,3       C7.8,13.8,7.6,13.9,7.5,13.9z"/>
                </g>
            </g>
        </g>
    </g>
</g>
</svg>

Answer №1

When working with paths in SVG, it's important to note that the fill and/or stroke attribute may not override CSS styling (learn more here).

To ensure your desired styling is applied, you can directly set the style property like this:

<path style="fill:green" ...>

You can also achieve this using JavaScript:

element.setAttribute('style', 'fill: green');

If you are looking to address issues with 'single path' elements, remember to use querySelectorAll instead of querySelector. This will return a NodeList containing all matching elements.

var paths = doc.querySelectorAll("path"),
    i;

for (i = 0; i < paths.length: ++i) {
    paths[i].setAttribute('style', 'fill:green');
}

Keep in mind that the compatibility of methods like getSVGDocument() varies across browsers, so consider using alternatives like the .contentDocument property as explained here

Answer №2

What you're seeing here is not just a simple path, but rather the entire "stroke" has been converted into one large object. This can occur when exporting objects with intricate brush settings from different drawing programs. The same outcome can also be achieved using the Outline feature in Adobe Illustrator, if I remember correctly.

To prevent this, make changes to the original object in its respective illustration software and experiment with the following steps:

  1. Opt for a basic stroke without any brushes. This method could potentially resolve the issue.
  2. Remove the stroke in the original editor and add it using JS or CSS within the SVG file instead.

Answer №3

According to the approved solution, I have devised a sample to demonstrate how to click a button and alter the color path.

An important note:

In order for it to function properly, the HTML file must be hosted on a webserver (such as IIS). Otherwise, a.contentDocument will always return null.

This information is shared for those who may find it relevant.

        var svgDoc;
        function changeColor() {
            svgDoc = a.contentDocument;
            // retrieve the inner element by id
            var paths = svgDoc.querySelectorAll("path");
            // apply changes
            for (i = 0; i < paths.length; i++) {
                paths[i].setAttribute('style', 'fill:pink');
            }
        }

        var a = document.getElementById("alphasvg");

        // Adding a load event listener to the object is essential,
        // as it loads the svg doc asynchronously
        a.addEventListener("load", function () {

            // retrieve the inner DOM of alpha.svg
            svgDoc = a.contentDocument;
            // retrieve the inner element by id
            var paths = svgDoc.querySelectorAll("path");
            // apply changes
            for (i = 0; i < paths.length; i++) {
                paths[i].setAttribute('style', 'fill:green');
            }

        }, false);
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    
    <object data="test.svg" type="image/svg+xml" id="alphasvg"></object>

    <button onclick="changeColor()">Change Color</button>

    <script>
      
    </script>
</body>

& lt;/html>

Answer №4

By utilizing JavaScript, it is possible to modify the fill attribute directly without having to adjust the style attribute.

for (i = 0; i < paths.length: ++i) {
      path.setAttribute('fill', 'green');
}

This streamlined approach allows for updating only the fill property instead of both fill and style.

Answer №5

To change the color of the stroke on an SVG path, simply add the stroke property to the path element and specify the desired color using rgb, hex, or hsl values.

<path fill="none" stroke="#000000" d="M50 30 L50 -10 C50 -10 90 -10 90 30 Z" />

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

Implementing ViewChild in Angular 2 using ES5 syntax

I am currently developing an Angular 2 app using ES5. My goal is to create a component with a dynamically loaded view child that will load existing components. While I have seen examples in TypeScript, I am struggling to achieve the same functionality in ...

Unable to connect with controller after deploying asp.net mvc ajax call on server

For the first time, I am encountering a new issue. Although my code runs smoothly on my localhost, when I upload it to the server, I get a bad request error. The specific error message is: 400 (Bad Request) Below is the snippet of my code: Controll ...

What causes the disappearance of CSS styles when attempting to modify the className in react js?

I am currently working on a basic react application, and I am trying to dynamically change the name of a div element using the following code snippet - <div className={'changeTab ' + (page.login ? 'leftSide' : 'rightSide')} ...

When deploying on Vercel, template literals cannot be used inside the src attribute of an image in NextJS

My issue involves displaying the client's picture after authentication using a userdropdown menu. The process of showing the user's image and name works smoothly with nextAuth when utilizing useSession(). https://i.sstatic.net/kBBa9.png Display ...

"Encountering difficulties while setting up an Angular project

I am currently working on setting up an Angular project from scratch. Here are the steps I have taken so far: First, I installed Node.js Then, I proceeded to install Angular CLI using the command: npm install -g @angular/cli@latest The versions of the ...

What is the correct way to chain promises within Promise.all?

Essentially, I retrieve all the rows from a schedule table and then process each individual row. If the row is already in the command table, I skip it. Otherwise, I insert it. Within Promise.all(rows.map(function(row){ I have 2 chained promises: return ...

What is the best way to identify the differences between two non-unique arrays in JavaScript? I initially relied on underscore, but I am willing to

Given two arrays: firstArray = [{id: 'id1'}, {id:'id2'}, {id:'id3'}, {id:'id3'}] secondArray = [{id: 'id1'}, {id:'id2'}, {id:'id3'}] The expected output is [{id:'id3'}] This ...

Send a pair of values using a set of two parameters

My current code is currently passing only one parameter value. However, I would like to modify it to pass two values with two parameters. This is my current code: <script> function getfilter(str){ document.getElementById("result"). ...

Sending a series of values to PHP through jQuery

I am facing an issue with retrieving the checked rows values from a table column using jQuery and transmitting them to a PHP function for further processing. Currently, I have the following code: var searchIDs = $('input:checked').map(function( ...

Refreshing the page does not update the API requests

I have been working on implementing a feature in Angular 7 where clicking on a refresh button reloads the route (without refreshing the entire page) and refreshes the data by making all API calls again. The refresh click functionality is being used across ...

Creating a light-box feature for my ReactJS app with react-multi-carousel

I am working on an application where images are fetched from a rest api and displayed in a react-multi-carousel. I want to make these images clickable for a light-box effect. As someone new to React, I have included my code for the carousel slider below: ...

What is the proper method for sending a value using the XMLHTTPRequest Object?

In my table, I have a set of dynamically generated links. Each row in the table has a unique "id" property in its tag. The main objective is to use XMLHTTPRequest to inform the 'deletepost.php' page which specific record needs to be removed from ...

What might be causing me to only view a black background while using ThreeJS in conjunction with VueJS?

Hey there! I recently incorporated a new component into my project that utilizes ThreeJS. My intention is to create a visually appealing scene with a light background and two boxes. However, despite my efforts to render the boxes, all I see is a black back ...

Using jQuery AJAX, the value of a server-side control (textbox) can be easily set

After working with the code below, I noticed that I can only set the value received from an ajax call if I am using HTML controls like buttons and text boxes. If I try to use asp server controls such as a button, the ajax call does not return any output, e ...

Issue with Express.js res.append function: Headers cannot be set after they have already been sent

I encountered an issue in my express project where I tried to set multiple cookies using "res.append" in the same request, but I kept getting an error saying "Error: Can't set headers after they are sent.". Can someone help me identify the problem and ...

Creating a dynamic effect to blur slideshow content located underneath a specific div

Struggling to figure out how to achieve a blur effect on a slideshow with moving elements? Most resources focus on static images, but I need help with objects in motion. My project involves a jQuery Cycle slideshow, and I want the background areas of over ...

Display various messages when submitting a form based on Ajax technology

I have been working on a script that utilizes AJAX to process form submissions. While I can successfully submit the form using AJAX and display a success message, I am looking to customize the messages based on the background data processing of the form. ...

Error in Node.js: Attempting to access properties of undefined

RV = (typeof myresult.CDF.UTILITYTYPE.D2.INSTPARAM[0].VALUE !== 'undefined') ? myresult.CDF.UTILITYTYPE.D2.INSTPARAM[0].VALUE : 'NA'; When attempting to fetch the value from the code above, I encounter an issue. If the key does not exi ...

Is there a way I can ensure the values are loaded when the page loads, rather than displaying NaN?

I've recently created a car rental calculator for a client, and it's almost complete. Everything is working smoothly, from the calculations to the conditions. However, I'm facing an issue where the price isn't calculated on page load. I ...

A JavaScript right-click menu that updates a variable when clicked

Within my three-dimensional application created with three.js, I have implemented a functionality where right-clicking on floors (BoxGeometry) triggers a context menu to select from various textures. While this feature works as intended for a single floor, ...