I am working with an SVG that is directly placed into an HTML file
<svg> Contents... </svg>
Using javascript/jQuery I want to add an attribute to the SVG
$("svg").attr("viewBox", "0 0 166 361");
Here is the modified SVG after running the above script
<svg viewbox="0 0 166 361"> Contents... </svg>
notice it puts viewbox not viewBox. Since viewbox (lowercase) doesn't do anything I need it to be viewBox (camelcase)
Any ideas?
** Update **
I ran a little test where I rendered the viewBox attribute from the server side, then I ran the script above. You can see that 1. When rendered from the server side, it is fine. 2. jQuery didn't recognize the camelCase viewBox attribute and inserted another one in all lower case.
<svg version="1.1" id="Layer_1" x="0pt" y="0pt" width="332" height="722" viewBox=" 0 0 100 100" viewbox="0 0 166 332"> ... </svg>
I might depend on your encoding document type. XHTML documents must use lower case for all HTML element and attribute names. I'm not sure about HTML.
Update 2
The only solution I could find is to use:
$("svg")[0].setAttribute("viewBox", "0 0 166 361");
Update
I can't explain it for any reason, I tested on my own host because JsFiddle always uses XHTML (boo!). In all cases it was lowercase, but it was still an SVG Element in FF, Chrome and IE9 (I don't know if they were valid because I don't know SVG I'm afraid).
Because html is case insensitive and xhtml tags and attributes should be lower case, jQuery converts the attribute name to lower case. Because xml is case sensitive, it's an issue for embedded xml language when they use camel case attribute names like SVG does.
You could use jQuery hooks to handle those attribute names you would like the case to not be converted. If jQuery find jQuery.attrHooks[attributename].set
to be set it will use it to set the attribute. Same for jQuery.attrHooks[attributename].get
when it tries to retrieve the attribute value. E.g.:
['preserveAspectRatio', 'viewBox'].forEach(function(k) { $.attrHooks[k.toLowerCase()] = { set: function(el, value) { el.setAttribute(k, value); return true; // return true if it could handle it. }, get: function(el) { return el.getAttribute(k); }, }; });
Now jQuery will use your setter/getters to manipulate those attributes.
Note: el.attr('viewBox', null)
would failed; your hook setter won't be called. Instead you should use el.removeAttr('viewBox').
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With