0

I can't get the 'width' attribute of an element:

console.log(document.querySelector('.container').width)
    <div class="container" width="55"> 


    </div>

This returns "undefined", other attributes like "id" I can get this way, but not width and height. I find this problem so silly, why doesn't it work? Even here they write it should work: https://www.w3schools.com/jsref/prop_object_width.asp

I don't need any workarounds like with jQuery or outerWidth, etc. I just need to get the width and height attributes from the element.

Edit: My actual problem is with SVG element, but with DIV it also doesn't work.

prk_001
  • 361
  • 3
  • 17
  • Are you trying to get the actual width, or the value inside the `width` attribute? (which is a legacy option on `div`s and may or may not have any effect on layout) – DBS Apr 13 '21 at 15:08
  • I need to get whatever is put into width="" in the html, not the actual width, not the styles width, only the exact value that is put into HTML. – prk_001 Apr 13 '21 at 15:12
  • Does this answer your question? [How do I retrieve an HTML element's actual width and height?](https://stackoverflow.com/questions/294250/how-do-i-retrieve-an-html-elements-actual-width-and-height) – Nora Apr 13 '21 at 15:22
  • Unfortunately it doesn't. I need to get data stored in width attribute, not to get actual width. – prk_001 Apr 13 '21 at 15:28

1 Answers1

4

You are looking for Element.getAttribute() (Documentation)

console.log(document.querySelector('.container').getAttribute('width'))
<div class="container" width="55"></div>
DBS
  • 9,110
  • 4
  • 35
  • 53
  • Thank you, yes this would work. But this doesn't have good enough support. I'd need something that works good on desktop and mobile. I thought that I can get any attribute of an element just by the . (dot), I am very suprised this doesn't work – prk_001 Apr 13 '21 at 15:17
  • It should be supported everywhere, [it's been around since IE5](https://caniuse.com/mdn-api_element_getattribute). Is there a specific situation where it's not working? – DBS Apr 13 '21 at 15:19
  • Not good enough support? It's been around forever and is supported by all modern engines. – Nora Apr 13 '21 at 15:21
  • Well I used to consider lack of Opera Mini support as not enough support. But, maybe it's time to leave it for e-commerce, after all nobody would buy anything by Opera Mini. So I will probably use getAttribute(). But do you know why doesn't it work? Why all the internet writes about taking width attribute this way (I'd say this standard way), but it actually doesn't work. – prk_001 Apr 13 '21 at 15:25