简体   繁体   English

无法使用 JS 获取元素的“宽度”属性

[英]Can't get 'width' attribute of an element with JS

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.这将返回“未定义”,其他属性如“id”我可以通过这种方式获得,但不是宽度和高度。 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即使在这里他们写它应该工作: 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 .我不需要任何解决方法,例如 jQuery 或 outerWidth 等。我只需要从元素中获取宽度和高度属性

Edit: My actual problem is with SVG element, but with DIV it also doesn't work.编辑:我的实际问题是 SVG 元素,但使用 DIV 它也不起作用。

You are looking for Element.getAttribute() ( Documentation )您正在寻找Element.getAttribute()文档

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM