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.

4
  • Are you trying to get the actual width, or the value inside the width attribute? (which is a legacy option on divs and may or may not have any effect on layout) Commented Apr 13, 2021 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. Commented Apr 13, 2021 at 15:12
  • Does this answer your question? How do I retrieve an HTML element's actual width and height? Commented Apr 13, 2021 at 15:22
  • Unfortunately it doesn't. I need to get data stored in width attribute, not to get actual width. Commented Apr 13, 2021 at 15:28

1 Answer 1

4

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

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

Sign up to request clarification or add additional context in comments.

4 Comments

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
It should be supported everywhere, it's been around since IE5. Is there a specific situation where it's not working?
Not good enough support? It's been around forever and is supported by all modern engines.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.