user399666
user399666

Reputation: 19909

Get "set" width of a given element

I have a div that needs to be given a width. i.e. A width must be manually set, either via CSS or via an inline style (Google Maps requires a set width and I'm trying to implement a fail safe, so to speak. If a developer messes up and fails to specify the width, I'd like to set a default width).

In my JS, I am checking like so:

var width = document.getElementById(this.divId).clientWidth;

Unfortunately, this is giving me back 1920px, even though a width has not been set (I understand why this is happening).

Is there a way to check if the width has been manually specified or not?

PS: I would like to do this without the aid of libraries such as JQuery.

Upvotes: 2

Views: 385

Answers (3)

kaos
kaos

Reputation: 1608

You can use DOM api jsFiddle

Style:

document.getElementById("test").style.width

Attribute:

document.getElementById("test").getAttribute("width")

Upvotes: 0

Alex Robert
Alex Robert

Reputation: 103

var width = document.getElementById(this.divId).getAttribute("width");

for getting the width attribute

 function getCSS(element, property) {

 var elem = document.getElementById(element);
 var css = null;

 if(elem.currentStyle) {

 css = elem.currentStyle[property];


 } else if(window.getComputedStyle) {


 css = document.defaultView.getComputedStyle(elem, null).
       getPropertyValue(property);

 }

 return css;



}

and this is for getting the css value of width or any other css attribute. you can verify the max or min of width and if it's not in the failsafe range you update with default value.

Upvotes: 1

j08691
j08691

Reputation: 208012

You can use getComputedStyle.

Ex: window.getComputedStyle(document.getElementById(this.divId),null).getPropertyValue("width")

jsFiddle example

Upvotes: 1

Related Questions