If I have a case sensitive attribute like nativeAttr
I can then use querySelector
to find the element by its attribute name.
But if I programmatically add a case sensitive attribute like setAttr
, then querySelector
no longer finds the html element.
How can I set the case sensitive attribute and also make it work with querySelector
?
const node = document.getElementById('node')
node.setAttributeNS(null, 'setAttr', 'set')
console.log('nativeAttr', document.querySelector('[nativeattr]')?.id)
console.log('nativeAttr', document.querySelector('[nativeAttr]')?.id)
console.log('setAttr', document.querySelector('[setattr]')?.id)
console.log('setAttr', document.querySelector('[setAttr]')?.id)
// the attribute is set in camelCase correctly
console.log(node.getAttributeNS(null, 'setAttr'))
// here are the names of the attributes; seems that nativeAttr is lowercase
console.log('nativeAttr', node.attributes[1].name, node.attributes[1].localName)
console.log('setAttr', node.attributes[2].name, node.attributes[2].localName)
<div id="node" nativeAttr="native"></div>
Case sensitive attributes are used by svg
elements, so it's a valid use case. For example:
// only one viewBox element
console.log(document.querySelectorAll('[viewBox]').length)
// add the viewBox attribute to the second svg
const svg2 = document.getElementById('svg2')
svg2.setAttributeNS(null, 'viewBox', '0 0 50 50')
// now both svg elements show up
console.log(document.querySelectorAll('[viewBox]').length)
<svg id="svg1" width="30" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
<circle cx="50" cy="50" r="50"/>
</svg>
<svg id="svg2" width="30" xmlns="http://www.w3.org/2000/svg">
<circle cx="50" cy="50" r="50"/>
</svg>
So, as you can see it works for svg
, but not for regular html elements.
According to the spec, uppercase letter are allowed in the attribute names.
In the HTML syntax, attribute names, even those for foreign elements, may be written with any mix of ASCII lower and ASCII upper alphas.