SnookSurvey: Element Attributes in JavaScript
I'd be interested to hear what the general consensus is on something. Consider this like a SimpleQuiz but not really simple and not really a quiz. More like a survey. SnookSurvey. And survey says...
I've got an element that I'm working with in JavaScript and I wish to get and set an attribute. How do you do it?
- Using
element.attribute
E.g.mylink.src = '/path/to/image.gif'
- Using
element.getAttribute('src')
E.g.mylink.setAttribute('/path/to/image.gif')
Which do you think is correct and maybe more importantly, which do you prefer?
Conversation
Depends how lazy I'm feeling. If I'm feeling particularly conscientious I'll use getAttribute/setAttribute, but otherwise I use the shorter version.
I use element.attribute because they work most predictably across browsers the only exception being creating elements where
setAttribute()
will set an attribute in a more literal way eg.element.setAttribute('disabled', 'disabled')
even then in IE you need to revert toelement.attribute
in some cases.element.attribute would be it.
element.attribute only works for some special attributes (except in IE). g/setAttribute works for anything.
For attributes, I generally use the property if it's available and otherwise the GSetAttribute methods. Properties have the advantage that you get e.g. absolute link uris instead of an relative link in the DOM.
When I'm just about to store some random data, I'll always use element.property, which won't pollute the DOM with invalid markup and doesn't limit me to strings.
I always prefer foo.setAttribute(), since it is *SUPPOSED* to be a cross-browser supported call... as is anything that calls this outside of the browser world... e.g. Java doing DOM manipulations.
that said, IE's support for this, is lackluster at best... so I've build stuff to fix IE to behave...
e.g.
.setAttribute('class', '...');
becomes...
.setAttribute('className', '...');
.setAttribute('for', '...');
becomes
.setAttribute('htmlFor', '...');
however, if in my code I'm already in the "fixing IE's silly bugs" mode... I may break down and just do...
iframe.style.frameBorder = 0;//IE is picky about the case of this attribute... ugh...
I prefer element.attribute cos it's simpler and how I used to do it back in the old DOM 0 days. But I actually use element.setAttribute as it's 'proper DOM' and so may have more longevity. Apart from setting classes when I use element.className because that works for IE.
I use the get/setAttribute. Makes my conscience feel better.
I also use get/setAttribute as it's just what I'm used to, and not for really any other reason.
I was using element.get/setAttribute() but it just seemed to be a long way round for something that was supported fine by using element.attribute. I didn't consider that one was the correct DOM way and one not; although I usually do.
I think the better question is: if they get rid of one, which can you live without? element.attribute seems more in tune with OOP so I would prefer to keep that one.
I believe that get/setAttribute is the correct way. That being said, I have ran into Internet Explorer not honoring all attributes correctly in this manner. For instance, try setting the onClick attribute using setAttribute. If I remember correctly, you'll run into some issues.
I use element.setAttribute(name, value) and I think this is the right way. But sometimes you don’t have that choise, especially when you’re coding for IE.
Have you ever tried to add an additional Eventhandler to the existing Eventhandlers of a body attribute like "onload"? It took me hours! Firefox and Opera allow to concatenate these function calls. IE don’t. Now I know that there’s a function called addEventListener() that is specified in W3C DOM and works well.
getAttribute() and setAttribute()
I don't necessarily feel one is more "correct" than the other, but I do prefer to use the DOM methods whenever possible.
That's an interesting question. IMHO, it arises solely because of one issue, IE's failure to distinguish between attributes of a DOM node and properties of a JavaScript object.
Technically, these two things are different. For some reason, IE got them mixed up. (I wrote an article about that a while ago).
That's why we had to implement
readAttribute
andwriteAttribute
DOM methods in Prototype (the latter is not included in a stable release as for now).Honestly, this is typically a situation where I'd favor using a library over using your own code. We went over tremendous testing efforts to ensure these methods were fully compatible in IE, Opera, Firefox and Safari, and trust me, it was a pain!
element.attribute, but I think there's one or two places where you need to use setAttribute() though I can't remember off the top of my head.
BTW, I think it's: mylink.setAttribute('src', '/path/to/image.gif');
I use a library and let it take care of it....
So what IE does is translate any calls to setAttribute into property setters, or in code:
becomes:
When writing IE only code (my work project at the moment) I tend to go for the property, otherwise I prefer to use setAttribute.
I'm with Tobie: Using element.attribute just causes problems with javascript's object properties.
I prefer to use element.attribute for quick and dirty work, but sometimes the setAttribute and getAttribute methods are necessary. When you're using custom attributes for example.
answer.setAttribute("choice", "b")
Brendon said: »I do prefer to use the DOM methods whenever possible«
It's a common misunderstanding that element.get/setAttribute is part of the official DOM and element.attribute is kind of proprietary. That's not entirely right. get/setAttribute is part of basic DOM Core which applies to all XML/SGML-style documents, (X)HTML amongst others. element.attribute is also standardized in DOM HTML, the special, additional DOM for (X)HTML documents.
We're using the special DOM HTML features all the time (e.g. document.body), they're handy, shorter and often faster (compare this to the DOM Core way: document.getElementsByTagName["body"].item(0)). Thus, I think it's okay to use the special DOM whenever it's possible. If it isn't (for example when dealing with non-(X)HTML nodes), fall back to DOM Core. But both techniques are officially standardized.
I use element.attribute="value";
I never had a reason to switch to get/setAttribute.
If I know that I can write 100% standards compliant code (for example Greasemonkey's UserJS), I use proper DOM -
set
/getAttribute
. For industrial use I choose HTML shorthands because they're supported everywhere (try settingclass
in IE. ;)Accidentally, because of IE's mapping of attributes to properties you can't use
setAttribute("class")
orgetAttribute("for")
. When mapped to properties these attributes are JavaScript keywords, and will therefore cause syntax errors.I usually use the element.attribute method, it might not be the *proper* way, but using mutators is just so against the general JavaScript coding style that I prefer to avoid it. I like to stay consistent with my coding style whenever possible. If I have problems with using the hash, I'll revert back to the mutators.
DOM, for no real reason. Perhaps because it just looks complicated :)
Using elem.attr = val; here as JS doesn't really have public/private datamembers on those objects (not to speak about crossbrowser compatibility). Would be nice though it there were, then we would be forced to use accessors ("getters") and mutators ("setters") making it all a wee bit more consistent with other scripting languages ...
In an ideal world, I'd use element.attribute when I'm wanting an attribute of the javascript object and element.getAttribute() when I'm wanting the value of an attribute node within the element.
The difference is noticeable in cases such as a src of an image, where getAttribute *should* return the content of the attribute src, whereas element.src returns the full path to the image.
Having said all that, 99% of the time I use element.attribute as it presents the least cross-browser issues.
I use get/set Attribute() because I have had problems with some sites with element.attribute. But for some occasions, like forms (element.value) or some specific attributes(className, id) is better to use direct link.
p.s. element.style and element.getAttribute('style') have a lot difference !
element.attribute
If I've decorated the element with custom attributes in the markup, I use (g|s)etAttribute for those attributes.
I've always used element.attribute. I find it more readable, I've never ran into a problem with it, and I don't foresee a day when a browser won't support it.
I always prefer the clean DOM version. You can nevertheless merge those two creating a function of your own if you want.
i use the getter/setter if i created the attribute for myself i want to manipulate.
and the direct access if it's a real html element-attribute as defined by w3c.
I use the second because it behaves like a proper object method, which is natural to me since I learned object oriented programming as a practice.
A
My general rule is: never use setAttribute and getAttribute when you can avoid them. There are just too many things wrong with their implementation. That said, I must admit that img.setAttribute('src','value') seems to have no bugs ... yet.
Note that element.attribute only works if the element (well, object) exposes an interface that has that attribute as member. This will not be the case for arbitrary XML nodes for instance or unknown attributes.
I always use element.attribute, but when I add an non-valid attribute to a node by JS, I noticed that you have to use .setAttribute. That's the only time I use it.
Btw: Neat website, add it to my feeds. Nice JS and layout.
I use setAttribute/getAttribute except where IE doesn't cooperate -- like with getting/setting class names.
I agree with PPK here, since some browsers (well, IE mainly) have poor/incorrect support for get/setAttribute I still mostly use element.attribute. This shouldn't be considered 'a rule' though, it's just practicing to the reality...
The element.attribute syntax is more in line with JavaScript and also has better support, so that's my preferred way in HTML. In XHTML or XML I of course use the namespaced functions though.
By the way, having document.createAttribute as well as document.createAttributeNS is just about as foreign an interface as you can get from JavaScript - the idea that we'd have two different functions when there is no clash in the semantics for when the functionality is called with one or two arguments respectively is just not very JavaScript -like.
These two methods are not equivalent.
For example, URI values such as a.href, img.src or form.method return absolute paths, while their DOM equivalents are strings that may represent relative or empty values. Also consider
input.checked == true
whereasinput.getAttribute("checked") == "checked"
.The right answer is that you should use different techniques based on the circumstances. The getter/setter properties a.href and img.src were around long before the DOM Level 1 spec, so these are sound to use for backwards compatibility. However, it is up to the browser vendor to implement these getters/setters for arbitrary DOM attributes, so you may find that obscure ones like
th.getAttribute("scope") != th.scope
in some browsers (hint: Safari 1.2).Well I just HATE the get/setAttribute. It is bigger and uglyer. And it is so limitating, one has to use strings. Actually I see this as a big mistake they've putted the get/setAttribute as the 'new default right way'. Why is it? Why should I call a function and pass string parameters to it, when I can just point directly to the property I want and change it?
I mean, the whole object oriented programming is about Object.subObject.property...
You just go deeper in the object using dots, it is perfect!
If you think about it, the get/setAttribute looks like it is the actual older way, and that the .property is the new simpler improved way.
I dont really get what is the point of this setAttribute thing...
Hey everybody! Cool forum! I’ve found so much helpful advice here.