Assigned width in percentage but want to get it in pixels

JqueryHtmlCss

Jquery Problem Overview


.test {
  border: 1px solid;
  cursor: pointer;
  height: 10px;
  position: relative;
  width: 100%;
}

<div id="test1" class="test"></div>

I have displayed my HTML id and its CSS. Now when I am doing $('#test').width() I am getting 100. I want its width in pixels (not in %).

Can anyone tell how to get its width in pixels?

Jquery Solutions


Solution 1 - Jquery

One of options can be too, that parent element is not visible. Here is example: http://jsfiddle.net/nDMM3/

You can see, that jQuery return width = 100 (like 100%)

.test {
    border: 1px solid;
    cursor: pointer;
    height: 10px;
    position: relative;
    width: 100%;
    display:none;
}

#test2{
   width:100%;
}
           
<div id="test1" class="test">
   <div id="test2">
      Hello
   </div>    
 </div>   
      
 alert($('#test2').width());

Solution 2 - Jquery

.width() gets "...the current computed width" of the element that is used on, per the jQuery width documentation: http://api.jquery.com/width/, so the return value from $('#heatMapBar').width() is in pixels, not percent. I would suggest using developers tool to check the width, it may be that in #heatMapBar's current context, its width is 100px.

If you look here: http://jsfiddle.net/NkQXa/1/ you will see that #test is set to width:50%;, but it alerts the actual pixel width.

Solution 3 - Jquery

There can be a problem with multiple divs having percentage width:

<div style="width: 50%">
<div id="getMyWidth" style="width: 100%"></div>
</div>

In this case it returns 100 as width for the inner div for me. I solved it by taking the width of the outer div.

Solution 4 - Jquery

Based on Honzik's answer there this is a small workaround in case the element needed to specify it's width is inside a hidden parent element.

function getWidth(elemID) {
    // get parent element unique id (must have)
    var parentId = $("#"+elemID).parent().prop("id"); 
    // remove the child element based on the specified element id
    $("#"+elemID).remove();
    // append a new child element but on body where most probably is not set to "display:none"
    $("body").append('<div id="'+elemID+'">Hello</div>');
    // get the width of the newly appended child element and store it to a variable
    var width = $("#test2").width();
    // remove child element from body
    $("#"+elemID).remove();
    // re-append child element to its former position under former parent element (having CSS attribute "display:none")
    $(parentId).append('<div id="'+elemID+'">Hello</div>');
    // display stored element width 
    alert(width);
}
// usage to get the element's width
getWidth("test2");

> Try it in the below snippet!

function getWidth(elemID) {
        var parentId = $("#"+elemID).parent().prop("id"); // your parent element should have a unique id specified
        $("#"+elemID).remove();
        $("body").append('<div id="'+elemID+'">Hello</div>');
        var width = $("#test2").width();
        $("#"+elemID).remove();
        $(parentId).append('<div id="'+elemID+'">Hello</div>');
        alert(width);
    }
getWidth("test2");

.test {
    border: 1px solid;
    cursor: pointer;
    height: 10px;
    position: relative;
    width: 100%;
    display:none;
}

#test2{
   width:100%;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test1" class="test">
   <div id="test2">
      Hello
   </div>    
 </div>

Solution 5 - Jquery

Another solution without jquery is to use the property clientWidth available on HTMLElements

document.getElementById('test1').clientWidth

Solution 6 - Jquery

That can be a co-incidence . According to the official documentation on api.jqery.com , it states that > Get the current computed width for the first element in the set of matched elements.

To confirm that you are getting the width in pixels , you can equate this value to .css(width) method of jQuery . It returns the width in pixels and hence , you can confirm that the return height is in Pixels.

Solution 7 - Jquery

Just an idea...don't hate. I know it doesn't cover every eventuality but something like this could check each of the items parents for the desired css rules (display:none; in this case). I got the idea from here.

The only problem is when a site gets more complicated...it becomes slow.

But it's a jumping off point.

//showing as 100%
alert($('#test2').width());
//use window.load to ensure .width() isnt doing anything funny
$(window).load(function(){
//checks to see if any of its parents have display:none; we can have multiple checks here if required
    if ($( "#test2" ).parents().css('display') == 'none') {
//iterate through each parent of the selected item  
	    $( "#test2" ).parents().each(function () {
//only change the display value if the element has a display:none;
	        if ($(this).css('display') == 'none') {
                $(this).css('display', 'block');
                alert($('#test2').width());//or whatever we want to do with this number
//reset values here       
                $(this).css('display', 'none');
           }
        });
    }
//showing as 100%
    alert($('#test2').width());
});

Solution 8 - Jquery

I am not sure about this fact but $("#id/.class").width() gives the value in pixels in my case.

screen-shot of jQuery code

In above screen-shot you can find different values of $("#id/.class").width() in pixels at different screen size of browser.

>Well I'm using Firefox for this purpose.

You can also check the http://api.jquery.com/width/">jquery documentation on this topic.

Solution 9 - Jquery

Pls check the code appended below, I hope this is the simplest way to get the width from percentage to pixel.

HTML

<div id="test1" class="test">
 <p id="widthPx"> Perentage to Pixel : </p>
</div>

CSS

 .test {
  border: 1px solid;
  cursor: pointer;
  height: 100%;
  position: relative;
  width: 100%;
  padding: 10px;
}

JS

var widPx = $('#test1').width();
$('#widthPx').append(Math.round(widPx) + 'px');

OUTPUT

Perentage to Pixel : 609px

The output would be purely based on the div width.

Thanks.

Solution 10 - Jquery

It could have been a bug in earlier jQuery versions, up to this Github PR: https://github.com/jquery/jquery/pull/3741

Although it's 2019 now, I had to use jQuery 1.12.4 and noticed that width computation of a hidden (hidden by parent) element was always 100.

By debugging, I found that the jQuery outerWidth (similar for innerHeight, innerWidth, height, width, outerHeight and outerWidth) function will call the width cssHook, which in turn calls getWidthOrHeight(). getWidthOrHeight() may obtain a width in %, which is then returned as it is. The width function does not check what was returned and passes it through parseFloat, which results in the 100% becoming just 100.

Solution 11 - Jquery

I think that should work, but if for some reason it keeps on giving you the % width, What you can do is get the width and then divide it by the window width

var widthInPx = $(widnow).width()/$('yourElement').width

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDenzzView Question on Stackoverflow
Solution 1 - JqueryJan JarčíkView Answer on Stackoverflow
Solution 2 - JqueryayypView Answer on Stackoverflow
Solution 3 - JqueryAxel SchmitzView Answer on Stackoverflow
Solution 4 - Jqueryuser2560539View Answer on Stackoverflow
Solution 5 - JqueryKalleView Answer on Stackoverflow
Solution 6 - JqueryDhruv RamdevView Answer on Stackoverflow
Solution 7 - JqueryMatthew BrentView Answer on Stackoverflow
Solution 8 - JqueryPankaj Kumar GautamView Answer on Stackoverflow
Solution 9 - JqueryKickyTrickView Answer on Stackoverflow
Solution 10 - JquerySP193View Answer on Stackoverflow
Solution 11 - JqueryreggaemahnView Answer on Stackoverflow