Skip to content

Getting the href value of an anchor within an SVG using jQuery

I am using jQuery to target anchor elements within an SVG image I have created to get the value of the href assigned to the anchor element. I am then trying to toggle on and off a piece of content that has an HTML ID identical to the href of the anchor element.

jQuery(document).ready(function ($) {
      $('object').on( "load", (evt) => { // wait for the page has fully loaded
        const svg_doc = $("object")[0].contentDocument;
        $('a[xlink\:href^="#"]', svg_doc )
          .on( "click", (evt) => {
            target = evt.currentTarget.href;
            console.log(target); // for debugging purposes
<object data="/wp-content/uploads/GHB_Interface-v0.1.svg" width="1400" height="1200"></object>
<div class="ghb_toggle" id="gable-pediments">content1</div>
<div class="ghb_toggle" id="gutters-downspouts">content2</div>
<div class="ghb_toggle" id="operable-shades">content3</div>

I am facing a problem when I assign the href value to the variable I created “target”. When I output the value of my variable $(target) in the console:

target = evt.currentTarget.href;


SVGAnimatedString {baseVal: "#gutters-downspouts", animVal: "#gutters-downspouts"}

This seems like it is successfully getting the href value of my anchor element! (the value should be “#gutters-downspouts”).

However, when I try to use jQuery to then toggle the respective html element with an ID that is identical to the href value like this:

target = evt.currentTarget.href;

I get the error:

Uncaught TypeError: Cannot read property 'display' of undefined

What the heck am I doing wrong? It seems as if it thinks my variable is undefined, however, I just printed it in the console and saw it had a value!


From the MDN documentation

SVGAnimatedString.animVal Read only This is a DOMString representing the animation value. If the given attribute or property is being animated it contains the current animated value of the attribute or property. If the given attribute or property is not currently being animated, it contains the same value as baseVal.

SVGAnimatedString.baseVal This is a DOMString representing the base value. The base value of the given attribute before applying any animations.

So you are successfully getting the information you need but it’s looking like an object with two entries. Try extracting the actual target value by using target.baseVal

(apologies that I have been unable to test this on a real system).