Replace text in a specific element?

  • 0
    There is a page that displays a bunch of tables with data.
    There is a script that finds certain words on the page with these tables, and replaces (adds) them with the div tag
    <script type="text/javascript">
    var htmlText = document.body.innerHTML;
    var newHtmlText = htmlText.replace(/Барнаул/g, '<div class="user-yellow">Барнаул</div>').replace(/Уссурийск/g, '<div class="user-red">Уссурийск</div>');
    document.body.innerHTML = newHtmlText;
    </script>


    There is one problem, there is a search on this page, and if you write "Barnaul" in the search, then as a result of the search everything moves out (since the search line also contains a replacement for Barnaul)

    Tell me how to make this script change values ​​only in the table itself
    JavaScript Landon Day, Oct 11, 2019

  • 2 Answers
  • 0
    Instead of

    document.body.innerHTML;

    Please specify

    document.querySelector ('. class'). innerHTML;

    Where, instead of class, you must specify the class of the element inside which you want to replace.
    Anonymous

  • 0
    Not body, but your table into this line

    var htmlText = document.body.innerHTML;

    Well, and accordingly, there is also a replacement for a table, instead of body

    document.body.innerHTML = newHtmlText;
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!