如果我有一個區分大小寫的屬性,nativeAttr我可以使用querySelector它通過屬性名稱來查找元素。但是,如果我以編程方式添加區分大小寫的屬性setAttr,則querySelector不再找到 html 元素。
如何設定區分大小寫的屬性并使其與它一起使用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>
元素使用區分大小寫的屬性svg,因此它是一個有效的用例。例如:
// 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>
因此,如您所見,它適用于svg,但不適用于常規 html 元素。
根據規范,屬性名稱中允許使用大寫字母。
在 HTML 語法中,屬性名稱,甚至是外來元素的名稱,都可以使用 ASCII 小寫字母和ASCII 大寫字母的任意組合來撰寫。
uj5u.com熱心網友回復:
屬性始終以小寫形式處理,因此如果您提供屬性nativeAttr,則會將其轉換為nativeattr.
正如HTML 標準中描述的那樣:
HTML 檔案中 HTML 元素上的所有屬性名稱自動變為 ASCII 小寫
建議使用帶有屬性名稱的 kebab-case。看看下面這個最小的例子:
const el = document.getElementById('node');
console.log('before', el.getAttributeNS(null, 'native-attr' ))
el.setAttributeNS(null, 'native-attr', 'changed');
console.log('after', el.getAttributeNS(null, 'native-attr' ))
<div id="node" native-attr="native"></div>
另請閱讀:html5 資料屬性是否區分大小寫?
uj5u.com熱心網友回復:
選擇命名空間屬性的適當字符是豎線字符 ( |)。如果沒有命名空間前綴,則在管道之前不使用任何內容,因此[*|setAttr]應該選擇您的元素。但是,在我的測驗中,它沒有這樣做,通過 CSS 也沒有querySelector:
const node = document.getElementById('node');
node.setAttributeNS(null, 'setAttr', 'set');
node.setAttributeNS('https://example.com/namespace', 'ns:someAttr', 'set');
console.log('html', node.outerHTML);
console.log('nativeAttr', document.querySelector('[|nativeAttr]')?.id);
console.log('setAttr', document.querySelector('[*|setAttr]')?.id);
console.log('someAttr', document.querySelector('[*|someAttr]')?.id);
@namespace ns url("https://example.com/namespace");
div[|nativeAttr] { color: blue; }
div[*|setAttr] { color: red; }
div[ns|someAttr] { color: green; }
<div id="node" nativeAttr="native">Ran</div>
即使提供了前綴和命名空間,該語法也不起作用,因此這似乎也是一個紅鯡魚。
這個答案不是一個答案,因為它是調查結果的檔案,以及演示應該如何作業的代碼。測驗在 Window 10 版本 10.0.19043.1466 上的 Microsoft Edge 版本 97.0.1072.62(官方版本)(64 位)中運行。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/416956.html
標籤:
