How to get the size of an element with a hidden parent?

1.4.4 returns the size of the hidden element, but what about the element in another hidden element? Is there a better solution then getWidth?

    <script type="text/javascript">
        function getWidth(element){
            var parent = element.parent();
            $('body').append(element);
            var width = element.width();
            parent.append(element);
            return width;
        }

        $(function(){
            var width = $("#foo").width(); 
            console.log(width); //0
            width = getWidth($("#foo"));
            console.log(width); //ok
        });
    </script>
    <div style='display:none'>
        <div style='display:none' id='foo'>bar</div>
    </div>
+3
source share
1 answer

When elements are hidden, their width may vary depending on the style. And when the hidden element is inside another hidden element, the results may change again. However, jQuery code is pretty simple:

$('#foo').parent().width()

This will grab the parent div foo and then grab its width, but I cannot guarantee that it will get the invisible natural width of the element. Hope this helps!

+1
source

Source: https://habr.com/ru/post/1781203/


All Articles