2 Replies - 1083 Views - Last Post: 07 April 2009 - 11:13 PM

#1 e_i_pi  Icon User is offline

  • = -1
  • member icon

Reputation: 801
  • View blog
  • Posts: 1,689
  • Joined: 30-January 09

JS not returning CSS object attribute values

Posted 23 March 2009 - 04:36 PM

From the code given below, I think it's pretty obvious what problem I'm having, but I'll explain:

Javascript is only returning HTML DOM attribute values when they are assigned by the javascript function, not when they are assigned by CSS. So, if I set the background colour of a div using CSS, then try to call that attribute value, JS doesn't return it, BUT, if I then assign a new value using JS, it can correctly read the attribute value.

What am I doing wrong? Or can javascript not pull HTML DOM attribute values assigned by CSS?

<html>

<head>

<style type="text/css">
.titlebar {background-color: #00ff00}
</style>

<script type="text/javascript">
  function clicky()
  {
	bg = document.getElementById("title");
	alert("Returning CSS-assigned value");
	alert(bg.style.backgroundColor);
	alert("Assigning new value");
	bg.style.backgroundColor = '#ff0000';
	alert("Returning new value");
	alert(bg.style.backgroundColor);
  }
</script>

</head>

<body>
  <div id="title" class="titlebar" onclick="clicky()">
  <h1>Blah Blah</h1>
  </div>
</body>

</html>



Is This A Good Question/Topic? 0
  • +

Replies To: JS not returning CSS object attribute values

#2 thehat  Icon User is offline

  • awake ? web();
  • member icon

Reputation: 106
  • View blog
  • Posts: 951
  • Joined: 28-February 08

Re: JS not returning CSS object attribute values

Posted 24 March 2009 - 06:15 AM

To get styles set through CSS, you need to use either getComputedStyle (most browsers) or currentStyle (IE). They are used like this:

<script type="text/javascript">
  function clicky()
  {
	bg = document.getElementById("title");
	alert("Returning CSS-assigned value");
	if(window.getComputedStyle) {
		//Mozilla, Opera, etc
		alert(window.getComputedStyle(bg,null).backgroundColor);
	} else {
		//Internet Explorer
		alert(bg.currentStyle.backgroundColor);
	}
	alert("Assigning new value");
	bg.style.backgroundColor = '#ff0000';
	alert("Returning new value");
	alert(bg.style.backgroundColor);
  }
</script>



These will work for styles set through javascript too.
Was This Post Helpful? 0
  • +
  • -

#3 forest51690  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 58
  • View blog
  • Posts: 340
  • Joined: 20-March 09

Re: JS not returning CSS object attribute values

Posted 07 April 2009 - 11:13 PM

And for attributes, which are parts of tags, like in this: <tag attribute="value"></tag>,

you can get the attribute's value by using the getAttribute() method
http://www.w3schools...etattribute.asp
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1