Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an element's padding value using JavaScript?

I have a textarea in my HTML. I need to get the padding numerical value in pixels as either integer or float. How can I get it using JavaScript? I am not using jQuery, so I'm looking for pure JavaScript solutions.

like image 597
R. Dewi Avatar asked Mar 08 '11 03:03

R. Dewi


People also ask

What is padding in JavaScript?

The padding properties define the space between the element border and the element content. Both the margin property and the padding property insert space around an element. However, the difference is that margin inserts the space around the border, while padding inserts the space within the border of an element.

What is the value of padding property?

The padding property in CSS defines the innermost portion of the box model, creating space around an element's content, inside of any defined margins and/or borders. Padding values are set using lengths or percentages, and cannot accept negative values. The initial, or default, value for all padding properties is 0 .

What is the padding of an element?

An element's padding area is the space between its content and its border. Note: Padding creates extra space within an element. In contrast, margin creates extra space around an element.

What is padding inherit?

Advertisements. The padding property allows you to specify how much space should appear between the content of an element and its border − The value of this attribute should be either a length, a percentage, or the word inherit. If the value is inherit, it will have the same padding as its parent element.


1 Answers

This will return the padding-left value:

window.getComputedStyle(txt, null).getPropertyValue('padding-left') 

where txt is the reference to your TEXTAREA element.

The above works in all modern browsers and in IE9. However, it does not work in IE8 and below.

Live demo: http://jsfiddle.net/simevidas/yp6XX/

Further reading: https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle


Btw, just for comparison, this is how you get the same job done using jQuery:

$(txt).css('padding-left') 

The above does work in IE6-8.

like image 104
Šime Vidas Avatar answered Sep 20 '22 12:09

Šime Vidas