setAttribute removeAttribute Methods Tutorial

Published :
Author :
Adam Khoury
Learn to apply the setAttribute and removeAttribute methods of JavaScript. Since JavaScript has become a necessary running component of the web and HTML5 relies heavily upon it we can lean on it more and more to reduce our HTML markup cosiderably much the same way we reduce our HTML markup by separating out the CSS styling from it. There are also times while a user is using your application, you may have to set or remove an HTML attribute from a tag at runtime. <!DOCTYPE HTML> <html> <head> <style> .someStyle{background:#FC0; padding:24px; font-size:24px;} </style> <script> function applyAttributes(){ document.getElementById("e1").setAttribute("align","center"); document.getElementById("e2").setAttribute("class","someStyle"); document.getElementById("e3").setAttribute("title","Navigate to my site"); } window.onload = applyAttributes; function applyAtt(target,att,attVal){ document.getElementById(target).setAttribute(att,attVal); } function removeAtt(target,att){ document.getElementById(target).removeAttribute(att); } </script> </head> <body> <h2 id="myHeading">The sky is blue and that is good.</h2> <input type="button" onClick="applyAtt('myHeading','title','Adam wrote this')" value="Click to add title attribute" /> <input type="button" onClick="removeAtt('myHeading','title')" value="Click to remove title attribute" /> <h2 id="e1">The sky is blue and that is good.</h2> <p id="e2">I cut three stacks of firewood today.</p> <a id="e3" href="http://www.developphp.com">Click my link</a> </body> </html>