3
votes

I am having this control and trying to get the offsetWidth,clientWidth and scrollWidth..

<span class="label-block" style="height: 19px; text-overflow: ellipsis; overflow: hidden; white-space: nowrap;">
<label for="ctl00_Form_PlaceHolder_chkIsAnnualSelfInsuranceRenewalCertificaterequired" id="tid" style="background-color:Transparent;">
Annual Self Insurance Renewal Certificate Required
</label>
 </span>

My code..

var a=$("#tid").offsetWidth;
var b=$("#tid").clientWidth;
var c=$("#tid").scrollWidth;

alert("offset Width =" +a);
alert("client Width =" +b);
alert("scroll Width =" +c);

The alert message displays as "Undefined" I have tried in Chrome and IE11 both results the same.

1
try logging those variables to make sure you have something in them first.ajmajmajma
the variables are created so it is not possible to have a value in them earlierGowthaman
You are mixing javascript and jquery. offsetWidth for example is used on a js object and you are trying to use it on a jquery objectHuangism

1 Answers

5
votes

Your $("#tid") returns an jQuery-object (with the DOM-label-element wrapped inside), but the three width are properties of the DOM-element itself. So you have to get the element itself:

var tid = $("#tid").get(0); // or:
var tid = $("#tid")[0]; // or with native javascript:
var tid = document.getElementById("tid");

Now you have the element itself stored in var tid (it's better than writing three times $("#tid")) and can do:

var a = tid.offsetWidth;
var b = tid.clientWidth;
var c = tid.scrollWidth;

According to the comments: these jQuery-methods works also in Chrome when element is display: inline;

var $tid = $("#tid"); // for jQuery-methods we need the jQuery-object

var e = $tid.outerWidth(); // corresponds to offsetWidth
var f = $tid.innerWidth(); // corresponds to clientWidth

Since jQuery has no direct equivalent for element.scrollWidth and inline-elements don't give reliable values for scrollWidth it would be best to set them to display: inline-block;.