I have a page that uses Javascript in order to produce content based on the response of a web service. The web service returns the content as a sentence ( string ) that sometimes contains an emoji (as image ) and presents the content on the page with a “Try This” button on the side.
When the user presses the button it triggers a function in order to capture the sentence that the web service sent us and place it in an input form.
My issue is that when the user clicks the button the function capture only the sentence without the emoji and place it to the input form.
The function that generates the button with the sentence.
if ( element.Example ) { $('.'+element.Mode) .parents('.card') .find('.list-check') .empty() .append('<li><span>'+element.Example.toString()+'</span> <a href="#" class="try-btn">Try This</a></li>'); }
The function that executes on click
$('body').on('click','.try-btn',function(){ var $val = $(this).prev('span').text(); $('input[name="sentence"]').val($val); });
Advertisement
Answer
If you only want the text and emoji, you can do this
const $elem = $('span'); let $img = $elem.find('img'); if ($img) $img.replaceWith($img.attr("alt")) $("#x").val($elem.text())
img { height: 20px }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <span><img draggable="false" role="img" class="emoji" alt="👉" src="https://s.w.org/images/core/emoji/13.0.1/svg/1f449.svg"> test </span> <hr/><pre> Text: <input type="text" id="x" />