Search code examples
jquerytextreplacefind

JQuery - Find and replace text


I'm trying to replace only the text of "Product Number/Description" to "Product Number". Here's the line of code:

<td><input type="checkbox" name="dessearch">&nbsp;Product Number/Description</td>

I've attempted the following, but it's also removing the input:

$("#ordersearch-page #content table tr td").text(function () {
    return $(this).text().replace("Product Number/Description", "test"); 
});

Any help would be greatly appreciated!


Solution

  • One option is to replace the HTML rather than the text. This will keep the <input> element.

    $("#ordersearch-page #content table tr td").html(function(i, oldhtml) {
      return oldhtml.replace("Product Number/Description", "test");
    });

    However, this will also lose any dynamic changes to the <input> element, such as the value the user entered, or event listeners.

    Another option is to put the text into a nested element so you can target it specifically.

    $("#ordersearch-page #content table tr td span").text(function(i, oldtext) {
      return oldtext.replace("Product Number/Description", "test");
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="ordersearch-page">
      <div id="content">
        <table>
          <tr>
            <td><input type="checkbox " name="dessearch "><span>&nbsp;Product Number/Description</span></td>
          </tr>
        </table>
      </div>
    </div>