As the title suggests, what's the difference(s)?
I guess that the latter one can do what the former can at least.
Is my opinion right?
P.S: obj is a DOM Element
As the title suggests, what's the difference(s)?
I guess that the latter one can do what the former can at least.
Is my opinion right?
P.S: obj is a DOM Element
One sets properties, the other sets attributes.
Some attributes map directly onto properties with the same name (such as <input type="password">
and myInput.type), some do not (such as
and
myInput.className. Some properties do not have an attribute (such as
myDiv.getElementsByTagName`).
Internet Explorer 7 and lower (and newer IEs in Quirks mode) have a bug where setAttribute
maps directly onto the property of the same name, no matter if the property and attribute do map to each other or not.
Note that square backet notation uses strings instead of identifiers so you can access properties on an object that can't be represented with an identifier. e.g. foo.bar
and foo['bar']
are the same but foo['bar-bar']
can't be represented using dot notation).
setAttribute
is a DOM Element method -- it can only be used on DOM elements. If you try to use it on your own objects a TypeError
will be thrown as they do not support that method unless you create it yourself. For example:
var myObject = {};
myObject.setAttribute('foo', 'bar'); // this will throw a TypeError
var myDiv = document.createElement('div');
myDiv.setAttribute('foo', 'bar'); // this works fine
However, the second method you have described is a valid way to assign properties and methods to your own objects and DOM objects (and there are a few special ones baked in for DOM objects in most browsers, such as onclick, like you've observed).
var myObject = {};
myObject.foo = 'bar';
console.log(myObject.foo); // --> 'bar'
console.log(myObject['foo']); // --> 'bar'
var myDiv = document.createElement('div');
myDiv.foo = 'bar';
myDiv.onclick = function() { console.log('clicked!') };
// same as: <div foo="bar" onclick="function() {console.log('clicked'!) }"></div>
You can read more about the Element interface and supported methods here: http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-745549614 (scroll down a bit for setAttribute)
One big difference would be in variable names - take the following example:
obj.what-ever = value;
/// syntax error - the parser attempts to subtract obj.what
/// from the nonexistent variable 'ever'.
obj.setAttribute('what-ever',value);
/// this works!
Also, AFAIK, obj.setAttribute is not a native javascript method - natively, you would set a key on an object with a non-allowed name like this:
obj['@#^&*^'] = value;
Hope that helps!