Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the attr() in jQuery force lowercase?

Tags:

I'm trying to manipulate the svg 'viewBox' attribute which looks something like this:

<svg viewBox="0 0 100 200" width="100" ...> ... </svg> 

Using

$("svg").attr("viewBox","..."); 

However, this creates a new attribute in the element called "viewbox". Notice the lowercase instead of intended camelCase. Is there another function I should be using?

like image 540
Ben Zuill-Smith Avatar asked Sep 11 '12 02:09

Ben Zuill-Smith


People also ask

What does ATTR do in jQuery?

jQuery attr() Method The attr() method sets or returns attributes and values of the selected elements. When this method is used to return the attribute value, it returns the value of the FIRST matched element.

How do I convert a string to lowercase in jQuery?

We can convert a String to lowercase in jQuery easily by using the JavaScript String toLowerCase() method.

Which jQuery DOM method is used to get the attribute value?

The jQuery attr() method is used to get attribute values.


2 Answers

I was able to use pure javascript to get the element and set the attribute by using

var svg = document.getElementsByTagName("svg")[0]; 

and

svg.setAttribute("viewBox","..."); 
like image 118
Ben Zuill-Smith Avatar answered Oct 11 '22 05:10

Ben Zuill-Smith


Per http://www.w3.org/TR/xhtml1/#h-4.2 "XHTML documents must use lower case for all HTML element and attribute names."

So in order to avoid having the attribute convert to lowercase in an XHTML document you need to create the element specifying a namespace using document.createElementNS(), like:

var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');     svg.setAttribute('viewBox', '0 0 512 512’); 

If you plan to add a <use/> element you also need to specify the namespace while creating the element as well as the xlink:href attribute, like:

var use = document.createElementNS('http://www.w3.org/2000/svg','use');     use.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', '#your_svg_id'); 
like image 21
Nick Hedberg Avatar answered Oct 11 '22 06:10

Nick Hedberg