db wrote:
Hi@all
Just got a comparison problem with javascript.
I want to compare :
document.getElementById(currentID).getAttribute("s tyle") with a string,
e.g: "background-color: lightgreen;" They are exactly the same, but
the execution result seems they are not equal. It works with firefox,
but not with IE.
My code is as following:
..............
var input = document.getElementById("someID");
var content = input.getAttribute("style");
if(content != "background-color: lightgreen;") <---this
comparison does not work with IE
input.style.background = "lightblue";
..............
I also tried
..............
var input = document.getElementById("someID");
if(input.style.background != "lightgreen")<---this comparison
does not work with IE either
input.style.background = "lightblue";
..............
Both of them work with Firefox. I really appreciate it if someone could
give me a hint.
cu
db
CSS implementations may vary from browsers to browsers. All of these
implementations have their up side, and down side. The example below
illustrate such implementations of the style properties :
---------------------------------------------------
<html>
<head>
</head>
<body>
<p id="par1" style="background-color: lightblue;">
Hello world !
</p>
<script type="text/javascript">
var test1 = 'lightblue';
var test2 = document.getElementById("par1").getAttribute('styl e');
if ( ( typeof test2 == 'string' &&
test2 == 'background-color: ' + test1 + ';')
|| test2['backgroundColor'] == test1 ) {
alert( 'equal' );
} else {
alert( 'not equsl' );
}
</script>
</body>
</html>
---------------------------------------------
As you can see, when test2 is a string, you have a (for exemple)
Mozilla browser, whereas style is an object (not necessary to compare
that one if it is not a stsring) you have a IE browser (since
implementations may vary from browser to browser, such affirmation is
somewhat bold, do not consider this as a universal truth).
Moreover, if the style should be "background: lightblue;" (yes, it's
valid CSS), or "background-Color:lightblue;", then only IE-like CSS
implementation would return "equal" even when the color is right.
I would suggest that you set classes to your elements, and compare
class names instead of style properties. Something like this :
-----------------------------------------
<html>
<head>
<style type="text/css">
fontClass { font-weight: bold; }
colorClass { background-color: lightblue; }
</style>
</head>
<body>
<p id="par1" class="fontClass">
Hello world !
</p>
<script type="text/javascript">
var test1 = 'colorClass';
var test2 = document.getElementById("par1").className;
if ( test2.indexOf( test1 ) -1 ) {
alert( "equal" );
} else {
alert( "not equal" );
}
</script>
</body>
</html>
-----------------------------------------
This way, you won't have to worry about how the CSS is written ; no
regular expression or ugly string manipulations.
Hope this helps.
-Yanick