Farooq Chohan
Farooq Chohan

Reputation: 23

How to define own js function for getting computed style of html elements

let element = id('mydiv'); // id() is element Selector by id
let style = getComputedStyle(element);
let eleHeight = parseInt(style.height);

I know I can get any style value using the js code above.

Now focus on the following.

function getCSS(css, element) {
    return parseInt(getComputedStyle(element).css);
}

// usage

let eleHeight = getCSS('height', id('mydiv')); // but it will return 'NaN'

I am trying to create my own instantiated function to do this. Please make it workable

Upvotes: 0

Views: 56

Answers (1)

Danny Yuan
Danny Yuan

Reputation: 105

You will need to use a string for the CSS property as object keys can be used like arrays or using the "dot" way.

function getCSS(css, element) {
    return parseInt(getComputedStyle(element)[css]);
}

let eleHeight = getCSS("height", id('mydiv'))

Upvotes: 1

Related Questions