Home > Mobile >  How to getComputedStyle of sub-element of div?
How to getComputedStyle of sub-element of div?

Time:03-26

Sorry in advance for the ESL choice of words. What I'm trying to get is the getComputedStyle of an h3 that's adjacent (?) or related (?) to a div which has a specific class (mainBook), while the h3 hasn't got any.

Here's an example of the CSS:

.mainBook 
{
     position: absolute;
}   
.mainBook h3
{
     line-height: 120px;
}

I know how to getComputedStyle of mainBook:

const element = document.querySelector('.mainBook');
const style = getComputedStyle(element);
// and then if I want: style.getPropertyValue("nameOfProperty")

Here's the HTML:

<div >
        <h3>Title</h3>
</div>

Not sure if this helps but:

const element = document.querySelector('.mainBook');
    const style = getComputedStyle(element);
    // and then if I want: style.getPropertyValue("line-height");
    // How do I getComputedStyle the h3?
.mainBook 
    {
         position: absolute;
    }   
    .mainBook h3
    {
         line-height: 120px;
    }
<div >
            <h3>Title</h3>
    </div>

But is there any way to do the same but for h3?

Thanks!

CodePudding user response:

1) You can get h3 element as

const element = document.querySelector('.mainBook h3');

and get its lineHeight from computedStyle as:

const style = getComputedStyle(element);
let lineHeight = style.lineHeight.

const element = document.querySelector('.mainBook h3');
const style = getComputedStyle(element);
console.log(style.lineHeight)
.mainBook {
  position: absolute;
}

.mainBook h3 {
  line-height: 120px;
}
<div >
  <h3>Title</h3>
</div>

2) You can also get h3 element from mainBook element as:

const mainBookEl = document.querySelector('.mainBook');
const headingEl = mainBookEl.querySelector('h3')
const style = getComputedStyle(headingEl);
const lineHeight = style.lineHeight;

const mainBookEl = document.querySelector('.mainBook');
const headingEl = mainBookEl.querySelector('h3')
const style = getComputedStyle(headingEl);
console.log(style.lineHeight)
.mainBook {
  position: absolute;
}

.mainBook h3 {
  line-height: 120px;
}
<div >
  <h3>Title</h3>
</div>

  • Related