Reputation: 123
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>
Upvotes: 2
Views: 7436
Reputation: 94
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();
Upvotes: 2
Reputation: 1539
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>
Upvotes: 0
Reputation: 2220
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>
Upvotes: 3