On the button click, I want to toggle its text from 'View More' to 'View Less'. However, the span element contains another element inside of it (Font Awesome icon). When I toggle text of a span element, the element inside of it disappears. You can see it in the snippet below.
I also tried this solution:
$('.button span').text(($('.button span').text()=='View More<i class="fas fa-angle-down"></i>') ? 'View Less<i class="fas fa-angle-up"></i>' : 'View More<i class="fas fa-angle-down"></i>');
But it inserts the i element as a span text, instead as an element.
NOTE: I can't keep the i element outside of the span element because I have certain animations in CSS.
$('.button').click(function() {
$('.button i').toggleClass('fa-angle-up fa-angle-down');
$('.button span').text(($('.button span').text()=='View More') ? 'View Less' : 'View More');
});
.button {
width: 250px;
padding: 12px 0;
text-transform: uppercase;
cursor: pointer;
}
.button i {
margin-left: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://kit.fontawesome.com/a671c6b423.js" crossorigin="anonymous"></script>
<button type="button" name="button" value="" class="button">
<span>View More<i class="fas fa-angle-down"></i></span>
</button>