开发者

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 par开发者_开发知识库ticular:

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 (e.g. 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, "")));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜