Home > front end >  how to remove a specific css from a div without adding an inline style?
how to remove a specific css from a div without adding an inline style?

Time:09-27

clicking on the button I need to remove the following css setting from #tg:

.wrap div{
text-align:justify;
text-align-last:left;
}

and add a acenter class - i.e. making it aligned center

#tgx.should not be changed

I can do it by $('#tg').css(...) but it adds an inline style which I want to avoid

$('button').on('click', function(){
  $('#tg').addClass('acenter');
});
.wrap div{
text-align:justify;
text-align-last:left;
}

.acenter{
  text-align:center;
  text-align-last:center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='wrap'>
<div class='tg' id='tg'>lorem ipsum</div>
<div class='tgx' id='tgx'>dolor sit</div>
</div>
<button>CLICK</button>

CodePudding user response:

You can add for them a class. For example, I add for them class oldClass. Then I can remove it by $('#tg').removeClass('oldClass');.

$('button').on('click', function() {
  $('#tg').addClass('acenter');
});
.wrap div {
  text-align: justify;
  text-align-last: left;
}

.acenter {
  text-align: center !important;
  text-align-last: center !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='wrap'>
  <div class='tg' id='tg'>lorem ipsum</div>
  <div class='tgx' id='tgx'>dolor sit</div>
</div>
<button>CLICK</button>

Update: I updated another solution by using !important to overwrite CSS because the author cannot add the HTML structure.

  • Related