开发者

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 respe开发者_如何学Pythonct 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/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.


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.


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.


No, it's not fine to do so. Most properties of DOM objects can be overwritten. You won't ruin the browser's behavior, since it doesn't use the DOM API. But you will ruin your JS scripts if they attempt to use the overwritten property in its original meaning.

My own way of doing things, when I have several attributes to attach to an object (as opposed to a single flag or link), is to create a custom object and then link it from the DOM element:

var Universe = {
  origin: "big_bang",
  creator: null,
  style: { deterministic: true }
};
document.getElementById('universe')._universe = Universe;
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜