- This topic is empty.
Viewing 4 posts - 1 through 4 (of 4 total)
Viewing 4 posts - 1 through 4 (of 4 total)
- The forum ‘JavaScript’ is closed to new topics and replies.
The forums ran from 2008-2020 and are now closed and viewable here as an archive.
Home › Forums › JavaScript › How to get ASSIGNED CSS width of an element
I know a few ways of getting the width of an element (see Codepen below), but for a specific plugin I’m building, I need to get the width as it is assigned in CSS, because I need to assign it to another element.
So, not the calculated or computed width in pixels, but the actual value that’s set in the CSS. If that’s “66%”, then the other element should also get a width of “66%” assigned to it. If it’s “100.5px”, then the other element should also get “100.5px”.
Anyone know of a way of getting that value for an element? In the Pen below, I’d need to get “70%”.
(PS I don’t need to calculate the percentage, so saying “divide element width by parent width and there you have it” is incorrect.)
I modified this pen from an answer I found on SO:
http://codepen.io/kvana/pen/wWBzjL
It gets the width attribute directly from the stylesheet. Here is the original thread on SO:
http://stackoverflow.com/questions/16778814/read-css-property-from-stylesheet
Maybe that will work for you?
Thanks @bearhead, I’ll give that a go. I believe I tried that sort of method before and although it worked (somewhat), it did create performance problems and some other conflicts. But let’s see….
I think cssRules
is the way to go too. But there seems to be something incorrect with the script on SO. I think it should be this :
return [].some.call(sheet.cssRules, function (rule) {
Using sheet.rules
is for old IE, I believe. Here’s a pen I made that also uses it – there is a small regex in there too in case of a selectorText
with multiple identifiers :
http://codepen.io/Shikkediel/pen/QwKMBQ?editors=0010
Some of it might be handy.