0

i need to check style.width with an js if statement. But it is not working. How can i do that?

My if code:

if (document.getElementById("XXX").style.width == "100%")
{

}
ats
  • 69
  • 7
  • The code seems fine, are you sure the element to compare is correct (not a typo/undefined content)? – Gabriel Domene Mar 10 '21 at 19:31
  • If the element with id "XXX" has its width explicitly defined as "100%", it should work. If the element is undefined, there should be an error "cannot read property style of undefined". I think the style of the element is not { width: 100% }. – Robin Michay Mar 10 '21 at 19:32
  • I am running this if block in a function, that called by another function. Can it cause that? – ats Mar 10 '21 at 19:33
  • Is the `width` set in a stylesheet (either in the `` of the document or elsewhere) or is it set using the `style="width: 100%"` using the inline `style` attribute? If it's set in the `style` attribute your code should work (although as written it doesn't do anything, have you added an `else { //do something else }` condition to your script? If it's set using a stylesheet then you need to use `window.getComputedStyle(document.getElementById('XXX'), null).width` to retrieve the width, though it's will be returned in pixel units, not the string `100%`. – David Thomas Mar 10 '21 at 19:40
  • If there's no `width: 100%` set on the element this won't work. If you want to get the actual width there's multiple options like offsetWidth etc – Phix Mar 10 '21 at 19:42

1 Answers1

-1

As the "width" style could actually be empty (not be there), I would personally check that too.

var elm_width = document.getElementById("XXX").style.width;
if(elm_width && elm_width == "100%"){
  ...
}

or even, depending on the script flow...

var elm_width = document.getElementById("XXX").style.width;

if(elm_width){
  if(elm_width == "100%"){
    ...
  }
}else{
  console.error('No width for element');
}

NOTE: Of course, this is if you need the actual CSS width. If you want to get the visual element width, as suggested before, there are other JS methods.

SomeDev
  • 15
  • 2
  • 6