JavaScript Answers

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

Spread the love

To get an element’s padding values using JavaScript, you can use the window.getComputedStyle() method.

To do this we write:

<!DOCTYPE html>
  <title>Get Element's Padding</title>
    #myElement {
      padding: 20px;
      background-color: lightblue;

<div id="myElement">This is a div element.</div>

  // Get the element
  var element = document.getElementById("myElement");

  // Get the computed style of the element
  var computedStyle = window.getComputedStyle(element);

  // Get the padding values
  var paddingTop = computedStyle.getPropertyValue('padding-top');
  var paddingRight = computedStyle.getPropertyValue('padding-right');
  var paddingBottom = computedStyle.getPropertyValue('padding-bottom');
  var paddingLeft = computedStyle.getPropertyValue('padding-left');

  // Log the padding values
  console.log("Padding Top:", paddingTop);
  console.log("Padding Right:", paddingRight);
  console.log("Padding Bottom:", paddingBottom);
  console.log("Padding Left:", paddingLeft);


In this example, we first get the element by its ID using document.getElementById().

Then, we use window.getComputedStyle() to get the computed style of the element, which includes all styles applied to the element, including padding.

Finally, we use getPropertyValue() method to retrieve the values of padding-top, padding-right, padding-bottom, and padding-left properties.

Keep in mind that the values returned by window.getComputedStyle() are in pixels (px) by default, but you can use additional functions to convert them to other units if needed.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *