Categories
JavaScript Answers

How to Get an Element’s Padding Value Using JavaScript?

Spread the love

Sometimes, we want to get an element’s padding value using JavaScript.

In this article, we’ll look at how to get an element’s padding value using JavaScript.

Get an Element’s Padding Value Using JavaScript

To get an element’s padding value using JavaScript, we can use the getComputedStyle and getPropertyValue methods.

For instance, if we have the following HTML:

<div style='padding: 20px'>  
  hello world  
</div>

Then we can get the padding-left value of the div by writing:

const div = document.querySelector('div')  
const paddingLeft = window.getComputedStyle(div, null).getPropertyValue('padding-left')  
console.log(paddingLeft)

We call document.querySelector to get the div.

Then we call window.getComputedStyle with the div to get the computed CSS styles of the div.

Then we call getPropertyValue with 'padding-left' to get the padding-left CSS property value.

Therefore, paddingLeft is '20px' according to the console log.

Conclusion

To get an element’s padding value using JavaScript, we can use the getComputedStyle and getPropertyValue methods.

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 *