1

I need to rewrite the display: none !important; for display: block; with javascript

I'm using this code below, but it has only worked on mobile browsers

document.getElementById('billing_state_field').style.setProperty("display", "block", "important");

For some reason in Google Chrome and Firefox the style has not changed

This is the page I'm trying to change. https://vegazcomm.com/finalizar-compra/

(You may need to add an item to the cart and click buy to reach the page)

The idea of ​​the code is to make the address fields appear only after the user touches the Post Code input

To make the fields disappear I had to use display: none! Important; on css and overwrite with JS.

The complete code is here

<script>


window.onload = function(){
    document.getElementById('billing_postcode').onclick = function(){
    //console.log('Hello world');
   
document.getElementById('billing_address_1_field').style.setProperty("display", "block", "important");

document.getElementById('billing_address_2_field').style.setProperty("display", "block", "important");

document.getElementById('billing_billing_number_field').style.setProperty("display", "block", "important");

document.getElementById('billing_city_field').style.setProperty("display", "block", "important");

document.getElementById('billing_state_field').style.setProperty("display", "block", "important");
  }
}


</script>
  • There is insufficient information to solve your problem. Please provide a minimal reproductible esample of your problem: https://stackoverflow.com/help/minimal-reproducible-example – Ortophius Feb 26 '21 at 21:53
  • !important always have higher priority so you will not be able to overwrite it. – Sunny Goel Feb 26 '21 at 21:55

2 Answers2

2

If inline !important does not work for you as you say, you can hardcode a solution like this:

var e = document.createElement('style');
e.innerHTML = '#billing_state_field {display: block !important;}';

document.body.appendChild(e);
#billing_state_field {
  display: none;
}
<div id="billing_state_field">
  billing_state_field
</div>
Moodland
  • 132
  • 5
  • You're adding a class to the element, but class selectors is less specific, so the rule from id selector will be applied even if both has an `!important` attribute. You need to change or remove the 'id' first then. – Ortophius Feb 26 '21 at 22:11
  • 1
    Edited for better solution – Moodland Feb 26 '21 at 22:16
1

You need to remove the current !important rule or add new new css rule with !important.

In both cases, you need to access document.stylesheets, find the ruleset with #billing_state_field selector and then change it.

More about adding !important rules via JS

MDN Docs

As alternative, you can just change the element's id like this:

document.getElementById('billing_state_field').id = ''

So the rules for #billing_state_field will not be applied for it.

Ortophius
  • 186
  • 2
  • 11