Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Return an objects style values

Status
Not open for further replies.
Aug 11, 2011
2
US
hello guys i used to be a good amateure programmer i been off for a few years and have rekindled my intrest! I was never good lol just capable in the most inefficient sense. Any who to the point....

im trying to return style values of div for example an theoretical external style sheet....

#myDiv {
color:red;
display:block;
width:100px;
height:100px;
}
I am having trouble rertuning the values i either get undefined or blank.

var myTest=document.getElementById('myDiv').style.color;
this returns a blank value.

var myTest=document.getElementById('myDiv').style.color.value;
this returns "undefined".

thanx in advance guys!

 
Javascript can only retrieve style values it has set. Properties set by a stylesheet cannot be read.





----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Behind the Web, Tips and Tricks for Web Development.
 
okm thanx i guess ill do it the hard way and make a perl script parsee the style sheet and have javascript declare the style attributes in when the page loads. thanx
 
Hi

One minor thing to add. Applied styles can be retrieved using [tt]getComputedStyle()[/tt]. As there are implementation differences across browsers, take the getStyle() function from Peter-Paul Koch's article, Get Styles and use it as [tt]myTest[teal]=[/teal]getStyle[teal]([/teal][green]'myDiv'[/green][teal],[/teal][green]'color'[/green][teal]);[/teal][/tt]. Note that for certain values the browsers will return the internal representation. ( For example the color in [tt]rgb()[/tt] notation. )

Feherke.
 
Why do you need to know what has been set in the styles?

If you need to set them, Js can still do that,

obj.style.color="#ff0000"; Would change the object's text color to red.

The next time you try to read it the RGB equivalent value will be returned as expected.

Alternatively you can have JS set the values upon loading the page, so you can retrieve them afterwards. Still not sure why you need to retrieve the entire style sheet for an object.






----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Behind the Web, Tips and Tricks for Web Development.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top