In DOM, is it OK to refer to an element’s attributes like this:
var universe = document.getElementById('universe');
universe.origin = 'big_bang';
universe.creator = null;
universe.style.deterministic = true;
? My deep respect for objects and their privacy, and my sense that things might go terribly wrong if I am not careful, makes me want to do everything more like this:
var universe = document.getElementById('universe');
if(universe.hasAttribute('origin')) then universe.origin = 'big_bang';
etc...
Is it really necessary to use those accessor methods? Of course it may be more or less necessary depending on how certain I am that the elements I am manipulating will have the attributes I expect them to, but in general do the DOM guys consider it OK to use .notation rather than getters and setters?
Thanks!
For XML documents, you must use
getAttribute/setAttribute/removeAttributeetc. There is no mapping from JavaScript properties to DOM attributes.For HTML documents, you can use
getAttributeet al to access attributes, but it’s best not to because IE6-7 has difficulties with it. The DOM Level 2 HTML properties are not only more reliable, but also easier to read.It’s unclear whether you’re using XML or HTML documents here. Clearly
originis not an HTML attribute; ‘custom’ elements and attributes like this should not be included in HTML documents. But it’s unclear whatuniverse.style.deterministicrefers to; you wouldn’t get a CSS style lookup mapped without an HTMLstyleattribute.