in javascript dom, are there rules to attribute names?

for meta data on the page using attribute names like table:rowNum:<name> , eg,

var row = document.createElement('tr');
row.setAttribute('tup','emp:1');
row.setAttribute('emp:1:pkid','123');

have been using colon-delimited names (eg, name='emp:1:emp_id' ) for years with good success, but today got bit with colon delimited attribute names

in particular:

var el2 = row.parentNode.querySelector("[emp:1:pkid]");
=> `Error: SYNTAX_ERR: DOM Exception 12`

are special character like ':' illegal in dom attribute names? can special characters be escaped to work with querySelector() ?


from chrome console:

> row.parentNode.querySelector('[emp:1:pkid]');
Error: SYNTAX_ERR: DOM Exception 12

as per James (below):

> row.parentNode.querySelector('[emp:1:pkid]');
123

but Problem - does not work with getAttribute - pia

> row.getAttribute('emp:1:pkid');
123
> row.getAttribute('emp:1:pkid');
null

It seems that you can escape the special characters with a double backslash:

var el2 = element.querySelector("[emp:1:update]");

I think the problem is to do with the fact that a colon would normally indicate a pseudo element.

According to the WHATWG spec, any characters except those that would change the context (eg an equals character, as that specifies the start of the value, or a greater-than character, which would specify the end of the tag). On that basis, it's fine to use colon characters in attribute names.

Update (based on comments on answer and updates on question)

To use one variable with both querySelector and getAttribute , you could do something like this, or you could just store the version with escaped characters, and one without (which would definitely be my preferred option):

var s = "emp:1:update";
console.log(row.getAttribute(s.replace(//g, "")));
链接地址: http://www.djcxy.com/p/54124.html

上一篇: PowerShell:读取PowerShell脚本日志

下一篇: 在javascript dom中,是否有属性名称的规则?