Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get the CSS maxWidth value of the parent javascript

I have these elements:

<div class="parent"><div class="child"></div></div>

css: .parent{max-width:100px}

Is it possible to get "max-width" value specified in css using "parentNode" of "child" (the name of parent is unpredictable) in order to compare it with the current variable data?

I was trying:

var childDIV=querySelector('.child');
var result= childDIV.parentNode.style.maxWidth`

"result" is empty.

Another attempt was using "getComputedStyle" method:

var result =window.getComputedStyle(childDIV.parentNode,null);
result.getPropertyValue("maxWidth");

"result" is empty although proper "maxWidth" value shows up among values of "getComputedStyle" .

var childDIV=document.querySelector('.child');
var result= childDIV.parentNode.style.maxWidth;
console.log(`Approach 1: ${result}`);

var result =window.getComputedStyle(childDIV.parentNode,null);
result = result.getPropertyValue("maxWidth");
console.log(`Approach 2: ${result}`);
 .parent{max-width:100px}
<div class="parent"><div class="child"></div></div>
like image 742
Serg Avatar asked Mar 05 '26 01:03

Serg


1 Answers

You were on the right track - so, your first approach does not work in this case because the element doesn't have max-width directly inside its style declaration (see sample below with .other for when this would work).

The second approach is correct, but you mixed up access argument a little - if you use .getPropertyValue, you use CSS-style "max-width", and if you don't, you use .maxWidth like with .style:

var childDIV=document.querySelector('.child');

var result= document.querySelector('.other').style.maxWidth;
console.log(`Approach 1: ${result}`);

var compStyle = window.getComputedStyle(childDIV.parentNode,null);

result = compStyle.maxWidth;
console.log(`Approach 2: ${result}`);

result = compStyle.getPropertyValue("max-width");
console.log(`Approach 3: ${result}`);
.parent{max-width:100px}
<div class="parent"><div class="child"></div></div>

<div class="other" style="max-width:50px"></div>
like image 107
YellowAfterlife Avatar answered Mar 07 '26 15:03

YellowAfterlife