0

I am trying to compare width of one element with "100%" with the below code. I wrote this code but did not work. Width of element is 100% . Please advice

if (document.getElementsByClassName("progress-bar")[0].offsetWidth ==="100%") {
    clearInterval(r1);
    clearInterval(r2);
    clearInterval(r3);
}
2

1 Answer 1

5

Your code is working correctly, but offsetWidth returns the physical pixel width of the element on the screen. Since you're doing a strict equality comparison using ===, the if() block never evaluates to true; offsetWidth returns an integer to start, and will never append the % value.

For example, see this jsFiddle demo -- the <input />'s value becomes an integer.

If you absolutely need to have the width as a percentage value, you'll need to access the element's CSS definitions using the HTMLElement.style property as follows:

document.getElementsByClassName("progress-bar")[0].style.width;

jsFiddle Demo

Ultimately, your if() block will become:

if( document.getElementsByClassName("progress-bar")[0].style.width == '100%' ) 
{
    clearInterval(r1);
    clearInterval(r2);
    clearInterval(r3);
}
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.