I’m experimenting with HTML, CSS and SVG files. I have an elaborate illustration saved as an SVG file. Inside this file, I have two elements with a unique ID: COLOR1 and COLOR2. As default they have a fill in Red (COLOR1) and Yellow (COLOR2).
I loaded the SVG file into the HTML page using the <object>
method. The SVG is too complicated to embed it inline and the page, after the experiment, can have more than only one SVG file of the same kind.
<object id="Soldier" type="image/svg+xml" data="ProvaSVG.svg" width="400" height="400">
<param name="src" value="ProvaSVG.svg">
</object>
I want to change, at page load, the colors of these two elements, according to different values supplied by a database. For example COLOR1 to Green and COLOR2 to Blue.
This is what I did:
Soldier.COLOR1.fill='Green';
Soldier.COLOR2.fill='Blue';
How I correctly address the elements to change their fill values? I want to use plain JavaScript, not jQuery or other dependencies.
2
Answers
contentDocument
style.fill =
You can load your externaL SVG file with my 7 line modern native JavaScript Web Component
<load-file>
Then inline it into your document, making all CSS possible.
With option to add (
replaceWith
) it to global DOM or into shadowDOM.Full docs: https://dev.to/dannyengelman/load-file-web-component-add-external-content-to-the-dom-1nd