28 March 2009

Set/Get (class) Attribute from JavaScript

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");
divSample.id = "secondID";

Way 2:

var divSample = document.getElementById("firstID");
divSample.setAttribute("id","secondID");

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>
<head>

    <title>Class Attribute in JavaScript</title>

    <style type="text/css">

        .normalbackground-color:Graycolor:Black;}       

        .highlightbackground-color:Yellowcolor:Red;}

    </style>   

    <script language="javascript">

        function setStyle(styleName)
        {
            var divSample = document.getElementById("myDiv");
            divSample.setAttribute("class", styleName);
        }
    </script>

</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>


0 Comments:

 

© 2007 t!ps n tr!cks: Set/Get (class) Attribute from JavaScript



Template unik dari rohman


---[[ Skip to top ]]---