7

In the Working with the Attribute Node chapter in Learning Javascript - A Hands-On Guide to the Fundamentals of Modern Javascript, the author Tim Wright said on Page 73:

Removing an attribute is as simple as getting one. We just target the element node and use the method removeAttribute() to get it out of there. There are no Javascript exceptions thrown if you try to remove an attribute that doesn't exist, but it's still best practive to use the same hasAttribute() method we mentioned earlier, shown in Listing 4.6.4

Listing 4.6.4 Javascript Used to Remove the Class Value of Our Image

if(document.getElementById("pic").hasAttribute("class")) {
    document.getElementById("pic").removeAttribute("class");
}

If there's no exceptions thrown either way, isn't checking whether it exists or not redundant? The same outcome will arise. The argument that the book says is that check for the paramenter before removing it saves the browser parsing through unneccesary code, but if(document.getElementById("pic").hasAttribute("class")) {} is even longer than document.getElementById("pic").removeAttribute("class"); on its own!

Why is this best practice then?

dayuloli
  • 16,205
  • 16
  • 71
  • 126
  • I did a performance test [here](http://jsperf.com/removeattribute-vs-condition-hasattribute), as you said, removeAttribute method is faster than hasAttribute check. so vote for your question here – fuyi Mar 21 '14 at 16:36
  • Thanks! For one thing...I didn't know about jsperf.com! – dayuloli Mar 21 '14 at 16:39
  • 3
    There is a faster check, dot notation: http://jsperf.com/checkattributeornot Both hasAttribute and removeAttribute are slow. – epascarello Mar 21 '14 at 16:40
  • Wow...I'm learning so much today! dot notation and everything! :D So @epascarello you are saying that the dot notation is the best practice, over the 'check method' or just removing it? Is the best practice dependent on just operations per second? What about the things that Weiwei said - about meta data and heavier function call? – dayuloli Mar 21 '14 at 16:42
  • 1
    I am not saying it is the "best" practice. It is an option for speed. Best practice is what some person with an opinion says you should do. – epascarello Mar 21 '14 at 16:49
  • This question is about why check for element/attribute before removing...the answer I would accept (if epascarello posts it) is that it could be faster. Off this, I have a different question of why is it faster. Since it is different from this question, I have asked in a different question here. http://stackoverflow.com/questions/22565494/why-is-checking-element-attributes-before-removing-it-faster-using-dot-notation – dayuloli Mar 21 '14 at 17:26
  • update: epascarello's link has the scenario where the attribute it's trying to remove doesn't exists. This link has the scenario where it does. The dot notation is still faster http://jsperf.com/checkattributeornot/6 – dayuloli Mar 21 '14 at 17:54
  • @epascarello: No, properties are very different from attributes! Neither is there an `.xxx` nor a `.class` property on DOM element. You might however use the `.className` property *instead* of dealing with attribute nodes. – Bergi Mar 26 '14 at 17:35

3 Answers3

3

In my opinion your assumption is absolutely right. I think the "advice" in the book is kind of catastrophic (to use a dramatic term). Havent heard about that "best practice" anywhere before. There is absolutely nothing you could achieve by using element.hasAttribute prior to removing / changing an attribute but slow down your code. A browser does not magically have a lookup list for attributes to check for their existence that is not used when it set or get an attribute. It may be best practice - in the authors opinion - for producing readable and understandable code, though.

Furthermore, in my opinion you should never use setAttribute at all! Use setAttribute only then there is no built in standard method for getting or setting a certain attribute. Here class is in question, use

element.className = 'myclass';

instead of

element.setAttribute('class', 'myclass');

Browsers have optimized routines when using such standardized methods. If not being used when you assign or delete an attribute to an element then the browser has to figure out what kind of attribute it is, and may perhaps trigger special operations afterwards - not everytime nessecary.

You can check if a browser supports a specific attribute-method like this

if (typeof window.document.body.className === 'string') {
   //className is supported for node elements
}

Most of those attribute-methods acts like getters and setters. You can read and write, and the use of some them are even more effective than other approaches. Example :

element.outerHTML = '';

clean more memory up than

element = null;

It is of course not an attribute to an element, but to show why one should prefer using built in methods targeting a specific part of an element.

There is many, many standard methods as element.className you can use to target a specific standard attribute. They are mostly named as the attribute name in camelcase notation. Use setAttribute only for your own custum attributes, like

element.setAttribute('data-my-custum-attribute', 'hello');

Which is perfectly legal markup according to the HTML5 standard. Or use it as a fallback, if the browser doenst support a certain attribute method. This can be the case for very old browsers. But even IE6 supports className.


I will recommend two books which I think is really valuable for understanding javascript in the depth (not claiming that I do in full, but those books have helped me a lot) :

Javascript - the good parts, by Douglas Crockford
Secrets of the JavaScript Ninja, by John Resig (the guy behind jQuery)

Buy the books! They are gold as reference on your desk.

Brad Larson
  • 170,088
  • 45
  • 397
  • 571
davidkonrad
  • 83,997
  • 17
  • 205
  • 265
  • 1
    They're simply called *properties* (in JS) or [*reflecting attributes*](http://www.whatwg.org/specs/web-apps/current-work/multipage/common-dom-interfaces.html#reflecting-content-attributes-in-idl-attributes) (in IDL), not "attribute-methods" – Bergi Mar 26 '14 at 17:40
  • 1
    and IDL is... https://stackoverflow.com/q/12354918 – djvg Apr 20 '23 at 08:50
0

One thing I have on my mind is that removeAttribute might be a much heavier function call regarding the operations it does, i.e., it modifies the DOM and HTML, and could also affects meta data in the browser.

In comparison, hasAttribute is just a read operation, which is much lighter and won't have impact on meta data. So it's better to check if the element has the attribute or not.

If removeAttribute itself already does hasAttribute checking, then I agree it is pretty much redundant.

Weiwei
  • 36
  • 3
-2

its useful for when you are writing a large program or working in a group.... you need to check that you dont remove something that is being used by something/someone else. if there is a more technical answer, hopefully someone else will supply it.

user3037493
  • 312
  • 2
  • 8
  • 1
    Thank you for your response...but either way, the element/attribute will be removed. All that extra code is doing is checking whether it exists before you remove it. – dayuloli Mar 21 '14 at 16:34
  • yes, that is why it would be a 'best practice' to check... not a technical requirement to use the remove function. best practice is defined by epascarello in the comments to your question :). it is up to you to determine if you want to use best practice or not. – user3037493 Mar 21 '14 at 16:58