71GA
71GA

Reputation: 1391

Getting other html elements from svg's external JS script

I have an svg image which I add in my .html document using <object> tags this:

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

I can then position the svg in .css file like this:

#bookmark{
            position: absolute;
            top: 0rem;
            left: calc(30rem - 0.1rem);
            z-index: 10;
            width: 1.25rem;
            height: auto;
}

So styling is working.

This svg should reveal a menu which slides from the left when svg is pressed. I tried implementing JS like this:

  1. I modified an svg:

    • I enabled sourcing to external JS by adding this attribute inside the <svg> tag.:

      xmlns:xlink="http://www.w3.org/1999/xlink"
      
    • I inserted a link to the external JS after the <svg> tag:

      <script xlink:href="../js/bookmark.js" />
      
    • I added an onclick insid the <path> tag:

      onclick="bookmark_click()"
      
  2. I created an external JS file ../js/bookmark.js with the folowing content:

    function bookmark_click(){
         console.log("Bookmark clicked.");
    
         let x = document.getElementById("menu");
         console.log(x);
    }
    

And I got this output in the browser's console:

enter image description here

It looks like external JS script can execute simple JS commands, but fails to see other elements in my webpage - we can see that x is returned as null. What am I doing wrong? I don't want to embed svg directly in my .html document.

Upvotes: 0

Views: 41

Answers (1)

Robert Longson
Robert Longson

Reputation: 123985

If the element with id="menu" is in the SVG's parent HTML document then you can use parent to get it i.e.

let x = parent.document.getElementById("menu") 

Upvotes: 2

Related Questions