Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In DOM is it OK to use .notation for getting/setting attributes?

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!

like image 986
Ziggy Avatar asked Mar 16 '10 04:03

Ziggy


3 Answers

For XML documents, you must use getAttribute/setAttribute/removeAttribute etc. There is no mapping from JavaScript properties to DOM attributes.

For HTML documents, you can use getAttribute et 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 origin is not an HTML attribute; ‘custom’ elements and attributes like this should not be included in HTML documents. But it's unclear what universe.style.deterministic refers to; you wouldn't get a CSS style lookup mapped without an HTML style attribute.

like image 142
bobince Avatar answered Oct 08 '22 15:10

bobince


Yes, it's fine ;-) If there's an attribute in the DOM, you can set it or get it, directly. No private or read-only elements or anything. By the way, JavaScript doesn't have a 'then' keyword.

like image 44
Silvanus Avatar answered Oct 08 '22 13:10

Silvanus


Due to cross browser issues I always use getAttribute and setAttribute:

if(!universe.getAttribute('origin'))
{
    universe.setAttribute('origin', 'big_bang');
}

I don't recall the specifics but I have had problems with the property style universe.origin and dynamically created DOM elements.

like image 24
row1 Avatar answered Oct 08 '22 14:10

row1