0

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>

4
  • Do you mean you want to dynamically add the acenter css properties to .wrap div css? Are you saying you don't want to use .addClass either? Commented Sep 26, 2021 at 9:05
  • You don't need to remove the text-align:justify if you add text-align:center after as that's how css works - the last defined property takes priority. Commented Sep 26, 2021 at 9:12
  • Can you specify what your expected end result would be? Commented Sep 26, 2021 at 9:13
  • 1
    @freedomn-m - click on button should result in #tg - centered - without affecting #tgx and without using inline style Commented Sep 26, 2021 at 9:28

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

unfortunatelly I can't. starting scenario is - as is
@qadenza Could you change the CSS?
@qadenza I add another solution by add !important in .acenter CSS.
seems it works. I'm just afraid if there is any hidden downside of using !important
@qadenza just make sure the order of .acenter in loaded CSS is the last. It will be fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.