setAttribute/getAttribute(“style”) crossbrowser alternative

The JavaScript methods setAttribute and getAttribute are very handy when you are designing dynamic effects for your website, but those methods have a lot of bugs in IE (6 an 7 at least), I use these two crossbrowser functions as alternatives instead of using directly setAttribute() and getAttribute(), I’ve been using them for quite a long time and have had excellent results (crossbrowser compatibility):

/* setStyle function */
function setStyle(element, styleText){
	if(element.style.setAttribute)
		element.style.setAttribute("cssText", styleText );
	else
		element.setAttribute("style", styleText );
}
/* getStyle function */
function getStyle(element){
 	var styleText = element.getAttribute('style');
 	if(styleText == null)
		return "";
	if (typeof styleText == 'string') // !IE
		return styleText;
	else  // IE
		return styleText.cssText;
}

Now use the setStyle function whenever you need to change the style attribite of a HTML element

Demonstration

Roll over this trigger:

setStyle and getStyle Test (using border and padding)

Explanation

On the demonstration we define two style for the div, the default one and one that we will swith to once we “mouseover” the div.

<script type="text/javascript">
/* <![CDATA[ */
/* Test */
var my_element = document.getElementById("test_div");
var my_trigger = document.getElementById("trigger");
var initial_style = getStyle(my_element);
var alternative_style = "border:solid 6px green;padding:6px";
my_trigger.onmouseover = my_element.onload = function (){
	setStyle(my_element, alternative_style);
};
my_trigger.onmouseout = function (){
	setStyle(my_element, initial_style)
};
/* ]]> */
</script>
Roll over this <a id="trigger" href="#" onclick="return false;" >trigger</a>:
<div id="test_div" style="border:solid 2px green;padding:10px">
  setStyle and getStyle Test (using border and padding)
</div>

<div style="display:n

//

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top