0

If I create the SVG within HTML and give the text items I want to change IDs, I have no problem accessing the ID using

let callQSO = document.getElementById("QSOcall").value; and then writing that to the SVG with

document.getElementById("SVGcallQSO").innerHTML = callQSO;


However for various reasons I want the SVG to be an external file, outside of HTML.

So I load the SVG file as an object

Then try to get the elements of the object from within JS with

let svgObject = document.getElementById('svg-object').contentDocument; from the console I can see this returns a null.

Can anyone offer any suggestion that would mean I can read the elelments from the external svg and manipulate them?

As always, grateful for any help.

I suspect I have a syntax problem somewhere, but where?

Derek
  • 1
  • 2
  • If it was a syntax problem, I'd rather expect you to get an _error_, not null. – CBroe Apr 18 '23 at 10:40
  • Have you tried this, https://stackoverflow.com/a/21503151/1427878 – CBroe Apr 18 '23 at 10:42
  • 1
    Please add an [Minimal minimal-reproducible-example StackOverflow Snippet](https://stackoverflow.com/help/minimal-reproducible-example) to your post. It will help readers execute your code with one click. And help create answers with one click. See [How to add a StackOverflow snippet](https://meta.stackoverflow.com/questions/269753/feedback-requested-runnable-code-snippets-in-questions-and-answers) – Danny '365CSI' Engelman Apr 18 '23 at 11:50
  • Please provide enough code so others can better understand or reproduce the problem. – Community Apr 18 '23 at 13:02

1 Answers1

0

You can't access an <object> DOm instantly.
You need to wait until the <object> DOM is loaded.
So you need to run your processing function calls in something like a load event

JS

var svgObject = document.getElementById("object");
// get svg content 
svgObject.onload  = (e)=>{
    let svgDoc = svgObject.contentDocument;
    let rect = svgDoc.querySelector('rect');

    //add click event
    rect.addEventListener('click', e=>{
      e.currentTarget.classList.toggle('active')
    })
}

Object

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

Test.svg

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">

    <style>
      .active{
        fill:#f00;
      }
    </style>

<rect x="0" y="0" width="100" height="100" fill="green"/>
</svg>

See running plnkr example

herrstrietzel
  • 11,541
  • 2
  • 12
  • 34