Pergunta

I've a trouble with the style of nav element in my web application.

enter image description here

As you're able to see, if to focus on element nav#menu.horizontal-menu - I can see the actual width/height of that element in Chrome.

BUT! When I try to obtain that element in JavaScript by the id - menu (as you can see the tag declaration of nav tag in the bottom part of screen):

enter image description here

There is no both width or height values of it... I rather understand, that it may be because of:

`nav#menu.horizontal-menu` != `nav`

But, it's only my suggestion... I've tried then to use both functions:

  • getElementsByClassName()
  • querySelector()

enter image description here enter image description here

But... also no success as you can see in screens, what's wrong and how to get so needed actual width and height options from element?

Thanks!

Foi útil?

Solução

I think you are looking for this answer:

How do I retrieve an HTML element's actual width and height?

.style.width only checks what is filled in in the style attribute of the element. OffsetWidth would probably work...

Outras dicas

That's because there are no width and height styles defined for it.

To calculate the rendered width and height, use a.offsetWidth and a.offsetHeight. Those are the values that DevTools are showing on hover.

Have you tried:

var width  = document.getElementById('foo').offsetWidth;
var height = document.getElementById('foo').offsetHeight;

For cross-browser compatibility I'm recommending you to use jQuery

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top