At the start I don't want .screen-text-page2 visibile, only after .screen-text-button-page1 is clicked
$('.screen-text-page2').removeClass("screen-text-page2");
$('.screen-text-button-page1').click(function() {
$('.screen-text-page2').addClass("screen-text-page2");
});
.screen-text-page2 {
background: pink;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button >Button</button>
<div >Div with class screen-text-page2</div>
CodePudding user response:
Short answer: Yes
The removeClass method is not a state... once you run it the class is removed and the element can accept any new class, including the same one.
If you want to re-add the class, then just add it again.
$("#ele").removeClass(".myClass");
$("#ele").addClass(".myClass");
is completely valid
CodePudding user response:
Yes, but because you're removing the class, you won't be able to select it again via $('.screen-text-page2')
. But if you save the selected element as a variable, you can reference it again without needing to reselect it using the class.
let page2 = $('.screen-text-page2');
$(page2).removeClass("screen-text-page2");
$('.screen-text-button-page1').click(function() {
$(page2).addClass("screen-text-page2");
});
.screen-text-page2 {
background: pink;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button >Button</button>
<div >Div with class screen-text-page2</div>
Another way to do something like this is to add another class before removing .screen-text-page2
, and then reselecting the element using this placeholder class. But in my opinion, that's just more steps than the above example.
$('.screen-text-page2').addClass("screen-text-page2-placeholder");
$('.screen-text-page2').removeClass("screen-text-page2");
$('.screen-text-button-page1').click(function() {
$('.screen-text-page2-placeholder').addClass("screen-text-page2");
});
.screen-text-page2 {
background: pink;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button >Button</button>
<div >Div with class screen-text-page2</div>