'Is there a way to select an element by class even though the class has been removed?
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 class="screen-text-button-page1">Button</button>
<div class="screen-text-page2">Div with class screen-text-page2</div>
Solution 1:[1]
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
Solution 2:[2]
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 class="screen-text-button-page1">Button</button>
<div class="screen-text-page2">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 class="screen-text-button-page1">Button</button>
<div class="screen-text-page2">Div with class screen-text-page2</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Shawn |
| Solution 2 | WOUNDEDStevenJones |
