2

When i tested it's will be alert blank value and 30px I want to get alert 400px and 30px How can i do ?

.div_cover_threads_image{
  width: 400px;
}
<div class="div_cover_threads_image">
test
</div>

<div class="div_cover_threads_image" style="width: 30px;">
test
</div>


<script>     
var div_cover_threads_image_Elem = document.getElementsByClassName('div_cover_threads_image');
for(var i=0, len=div_cover_threads_image_Elem.length; i<len; i++)
{
   alert(div_cover_threads_image_Elem[i].style.width);
}  
</script>
mamiw
  • 123
  • 4
  • 9
  • Possible duplicate of [How do you read CSS rule values with JavaScript?](https://stackoverflow.com/questions/324486/how-do-you-read-css-rule-values-with-javascript) – random_user_name Nov 07 '17 at 02:30
  • You've created some confusion by tagging `jQuery` but using vanilla `javascript` in your snippet. Which do you want? – random_user_name Nov 07 '17 at 02:31

3 Answers3

3

As you've tagged jQuery, this will return the elements width even if no width was explicitly defined:

.div_cover_threads_image{
  width: 400px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="div_cover_threads_image">
test
</div>

<div class="div_cover_threads_image" style="width: 30px;">
test
</div>


<script>     
var div_cover_threads_image_Elem = document.getElementsByClassName('div_cover_threads_image');
for(var i=0, len=div_cover_threads_image_Elem.length; i<len; i++)
{
   alert($(div_cover_threads_image_Elem[i]).width());
}  
</script>
Zeb Rawnsley
  • 2,210
  • 1
  • 21
  • 33
2

You used Element.style on the second div which means inline style. For the first one you need to use window.getComputedStyle(Element,[, pseudoElt]) in order to get all styles of it.

Extract the width by:

var width=window.getComputedStyle(Element,null).getPropertyValue('width');

The returned value will be something like 400px. If you wish to use the numeric value without unit, try parseFloat.

var els = document.getElementsByClassName( 'div_cover_threads_image' );
for(var i=0, len=els.length; i<len; i++)
{
    var computed = getComputedStyle( els[i], null );
    alert( computed.getPropertyValue( 'width' ) );
}

If you use jQuery, things will be more simple. Just $('.div_cover_threads_image').width();

Stev Ngo
  • 94
  • 4
0

From jquery,

.div_cover_threads_image{
  width: 400px;
}

<div class="div_cover_threads_image">
test
</div>

<div class="div_cover_threads_image" style="width: 30px;">
test
</div>


<script>     
$( ".div_cover_threads_image" ).each(function() {
  alert($( this ).width());
});
</script>
Casper
  • 1,469
  • 10
  • 19