skip to Main Content

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


    • Make sue that the object is loaded
    • Query the desired child element from the Object’s contentDocument
    • Use style.fill =
    <object id="Soldier" type="image/svg+xml" data="ProvaSVG.svg" width="400" height="400"></object>
    
    <script>
    const elObject = document.querySelector("#Soldier");
    
    elObject.addEventListener("load", () => {
      const elSVG = elObject.contentDocument.querySelector("svg");
      elSVG.querySelector("#COLOR1").style.fill = "green";
      elSVG.querySelector("#COLOR2").style.fill = "blue";
    });
    </script>
    
    
    Login or Signup to reply.
  1. 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

    customElements.define("load-file", class extends HTMLElement {
      async connectedCallback(
        src = this.getAttribute("src"),
        shadowRoot = this.shadowRoot || this.attachShadow({mode:"open"})
      ) {
        shadowRoot.innerHTML = await (await fetch(src)).text()
        shadowRoot.append(...this.querySelectorAll("[shadowRoot]"))
        this.hasAttribute("replaceWith") && this.replaceWith(...shadowRoot.childNodes)
      }
    })
    <load-file src="https://load-file.github.io/heart.svg"">
        <style shadowRoot>
          svg {
            height: 160px;
          }
          path:nth-child(2n+2) {
            fill: GREEN; /* shadowDOM style does NOT style global DOM */
          }
        </style>
    </load-file>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search