John St
John St

Reputation: 269

remove css property with pure js failed

I tried the following code to remove a property from my css but doesn't work.

 document.getElementById("wrap").style.removeProperty('overflow-x');

The CSS:

#wrap{
overflow-x : hidden;
}

When I run the javascript, I get the error Cannot read property 'style' of null

Upvotes: 0

Views: 656

Answers (1)

Joel Cox
Joel Cox

Reputation: 3469

The code posted would remove overflow-x style in the following scenareo:

<div id="wrap" style="overflow-x: hidden"></div>

CSS applied properties are not applied directly to the style attribute of an element - they are applied at a layer higher.

Effectively, there's nothing to remove on the style property, but you can set a value there instead, which would override the value applied from CSS properties (unless css has !important flag specified)

Try this instead:

document.getElementById("wrap").style.overflowX = 'visible';

As your specific scenario is about applying the style based on some browser detection, I suggest the following javascript:

var userAgent = window.navigator.userAgent.toLowerCase();
var is_ios = /iphone|ipod|ipad/.test( userAgent );
if (!is_ios) document.body.className += 'not-ios';

With CSS:

.not-ios #wrap {
    overflow-x : hidden;
}

You could also use class "wrap" instead of id to make this more re-usable (if required)

Upvotes: 4

Related Questions