Yan Kleber
Yan Kleber

Reputation: 405

Add custom attribute to SVG?

I have tried several forms of doing it but I am not getting it to work. I would like to know if there is a way of set custom attributes to a SVG element. My code:

var svgns = "http://www.w3.org/2000/svg";
var rect = document.createElementNS(svgns,'rect');
rect.setAttributeNS(null, 'x', 0);
rect.setAttributeNS(null, 'y', 0);
rect.setAttributeNS(null, 'height', 20);
rect.setAttributeNS(null, 'width', 20);
rect.setAttributeNS(null, 'fill', 'blue');
rect.setAttributeNS(null, 'id', '999');

// my attempt here
rect.setAttributeNS(null, 'foo', 'bar');

rect.addEventListener('click',
    function() {
        alert(this.foo);
    }
    ,false);

document.getElementById('yard').appendChild(rect);

So when I click the rect it should (by my guessing) alert the value of the attribute 'foo'. Instead it just output undefined.

Any clue?

Upvotes: 0

Views: 1506

Answers (1)

random
random

Reputation: 7891

use this.getAttribute('foo').

var svgns = "http://www.w3.org/2000/svg";
var rect = document.createElementNS(svgns, 'rect');
rect.setAttributeNS(null, 'x', 0);
rect.setAttributeNS(null, 'y', 0);
rect.setAttributeNS(null, 'height', 20);
rect.setAttributeNS(null, 'width', 20);
rect.setAttributeNS(null, 'fill', 'blue');
rect.setAttributeNS(null, 'id', '999');

// my attempt here
rect.setAttributeNS(null, 'foo', 'bar');

rect.addEventListener('click',
  function() {
    alert(this.getAttribute('foo'));
  }, false);

document.getElementById('yard').appendChild(rect);
<svg id="yard"></svg>

Upvotes: 1

Related Questions