I created the following button, and want to change the inner text "test" to other word.
<button type="button" id="test"><i class="fa-2x fa-regular fa-floppy-disk"></i>test</button>
I tried below method it can change the word but also deleted the icon.
$('button#bkmarktest').on('click', function(e){
e.preventDefault();
$(this).text("other");
});
Is there any way that can only change the word, but keeping the icon, thanks!
What .text() method does is that it overwrites not only text but HTML as well. The easiest thing to do is move your text inside the <i> so it doesn't get overwitten only what's inside of it. Review the example below and notice that the icon remains -- it's because it's actually a CSS pseudo-element and is always ignored by methods and functions dealing with the DOM.
$('.test').on('click', function() {
$(this).find('i').text(' IT WORKS!')
});
<link href='https://cdn.jsdelivr.net/fontawesome/4.7.0/css/font-awesome.min.css' rel='stylesheet'>
<button class='test' type='button'>
<i class="fa fa-star-o"> TEST</i>
</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I haven't use jQuery since very long so here's an example in vanilla javascript.
const btn = document.querySelector('#test');
btn.addEventListener('click', (e) => {
e.preventDefault();
// selecting span tag -> you can also give it a specific id or class if you want
btn.children[1].innerText = 'other';
})
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet"/>
<button type="button" id="test">
<i class="fa-2x fa-regular fa-floppy-disk"></i>
<span>test</span>
</button>
like @Kunal Tanwar said, wrapping the text in a span solves it and using Jquery this is my approach.. assuming the button has an id of test
using the .find() method to find the span child
<button type="button" id="test">
<i class="fa-2x fa-regular fa-floppy-disk"></i>
<span>test<span>
</button>
$('#test').on('click', function(e){
e.preventDefault();
$(this).find('span').text("other");
});
and another option would be to use the decendant selector since the span is a direct child of the button
$('#test').on('click', function(e){
$('#test > span').text('other');
});