0

Here is my code

pattern.setAttribute('id','test');
pattern.setAttribute('patternUnits', 'userSpaceOnUse');
pattern.setAttribute('width','10');
pattern.setAttribute('height','10');

in same code i have used like this,

pattern.attr('id','test','id','test','patternUnits','userSpaceOnUse','width','10','height','10');

but it's not working.. if i set the individual attribute using setAtribute working fine.. how to solve this. i want set attribute in single line. please find the jsfidle link http://jsfiddle.net/ubLr4/18/

Akbar Basha
  • 1,168
  • 1
  • 16
  • 38

1 Answers1

1

There's no native DOM function that sets multiple attribute in one go, and jQuery's attr wouldn't be appropriate for your SVG element because it makes the attribute names lowercase. You can readily add a function of your own to do the same thing as jQuery's attr without lowercasing, though:

function setAttributes(element, attrs) {
    var name;
    for (name in attrs) {
        if (attrs.hasOwnProperty(name)) {
            element.setAttribute(name, attrs[name]);
        }
    }
    return element;
}

Usage:

setAttributes(pattern, {
  id:'test',
  patternUnits: 'userSpaceOnUse',
  width: '10',
  height: '10'
});

Updated Fiddle

On most browsers (all modern ones), you could even add that to the SVGElement prototype:

SVGElement.prototype.setAttributes = function setAttributes(attrs) {
    var name;
    for (name in attrs) {
        if (attrs.hasOwnProperty(name)) {
            this.setAttribute(name, attrs[name]);
        }
    }
    return this;
};

Usage:

pattern.setAttributes({
  id:'test',
  patternUnits: 'userSpaceOnUse',
  width: '10',
  height: '10'
});

Updated Fiddle

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • @RobertLongson: Thank you for keeping Rory and I on our toes re the SVG thing and attribute casing. V. much appreciated. – T.J. Crowder Apr 28 '15 at 06:48