JavaScript is a client-side scripting language. It is designed for dynamically creating HTML element or changing it. There are some procedures for such kind of work. For example, consider the following HTML element. <div id="firstID">This is a sample div.</div> From JavaScript, you can change the attribute id of this div in either of the following two ways. Way 1: var divSample = document.getElementById("firstID"); Way 2: var divSample = document.getElementById("firstID"); From way 1, it is easily understandable that the attribute becomes an attribute of div object (divSample.id) which can be used for both set and get. From way 2, it is clear that attribute can be set by the function setAttribute(attributeName, attributeValue). Similarly, you can get by the function getAttribute(attributeName). In fact, both explanations are generally true. The attribute class is an exception. It is used for setting style from CSS. No browser accepts div.class attribute (like way 1). Again, different browsers behave differently for this attribute. Mozilla Firefox acceptsdiv.setAttribute("class", "styleName") procedure, while Internet Explorer acceptsdiv.setAttribute("className", "styleName") procedure (like way 2). Fortunately, all browsers accept div.className attribute. Sample Code: <html> <title>Class Attribute in JavaScript</title> <style type="text/css"> .normal{ background-color:Gray; color:Black;} .highlight{ background-color:Yellow; color:Red;} </style> <script language="javascript"> function setStyle(styleName) </head> <body> <div id="myDiv" class="normal"> This is a sample div.</div> <input type="button" value="Highlight" onclick="setStyle('highlight');"/> <input type="button" value="Normal" onclick="setStyle('normal');" /> </body> </html>
divSample.id = "secondID";
divSample.setAttribute("id","secondID");
<head>
{
var divSample = document.getElementById("myDiv");
divSample.setAttribute("class", styleName);
}
</script>
0 Comments:
Post a Comment