Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting 'xlink:href' attribute of the SVG <image> element dynamically using JS in HTML DOM

Tags:

dom

svg

xlink

I have a construction:

<div id="div">
    <svg xmlns="http://www.w3.org/2000/svg" version="1.1" id="svg">
        <image x="2cm" y="2cm" width="5cm" height="5cm" id="img" xlink:href="pic.jpg"></image>
    </svg>
</div>

I want to get pic.jpg url and I need to begin from the most outer div, not exactly from the source <image> element:

var div = document.getElementById("div");
var svg = div.getElementsByTagNameNS('http://www.w3.org/2000/svg', 'svg')[0];
var img = svg.getElementsByTagNameNS('http://www.w3.org/2000/svg', 'image')[0];
var url = img.getAttribute('xlink:href');   // Please pay attention I do not use getAttributeNS(), just usual getAttribute()

alert(url);     // pic.jpg, works fine

My question is what is the right way to get such kind of attributes from element like SVG and its children?

Because before I tried to do this way and it also worked fine in Chrome (I didn't try other browsers):

var svg = div.getElementsByTagName('svg')[0];   // I do not use NS
var img = svg.getElementsByTagName('image')[0];
var url = img.getAttribute('xlink:href');  // and do not use getAttributeNS() here too

alert(url);     // pic.jpg, works fine

But when I tried to use getAttributeNS() I got blank result:

var svg = div.getElementsByTagNameNS('http://www.w3.org/2000/svg', 'svg')[0];
var img = svg.getElementsByTagNameNS('http://www.w3.org/2000/svg', 'image')[0];

// Please pay attention I do use getAttributeNS()
var url = img.getAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href'); 

alert(url);     // but I got black result, empty alert window
like image 306
Green Avatar asked Sep 14 '12 10:09

Green


People also ask

How do I use Xlink HREF in SVG?

For <altGlyph> , xlink:href defines the reference either to a <glyph> element in an SVG document fragment or to an <altGlyphDef> element. If the reference is to a <glyph> element and that glyph is available, then that glyph is rendered instead of the characters that are inside of the <altGlyph> element.

Can I use SVG use href?

use. For <use> , href defines a URL referring to an element or fragment within an SVG document to be cloned. The <use> element can reference an entire SVG document by specifying an href value without a fragment. Such references are taken to be referring to the root element of the referenced document.


1 Answers

The correct usage is getAttributeNS('http://www.w3.org/1999/xlink', 'href');

like image 82
Robert Longson Avatar answered Nov 13 '22 14:11

Robert Longson