Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 339
cc young Avatar asked Aug 03 '11 18:08

cc young


1 Answers

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, "")));
like image 185
James Allardice Avatar answered Nov 06 '22 22:11

James Allardice