1

The code below shows a rendered HTML (from Compiled content management system). I would not be able to make any changes to it including adding new attributes like ID.

Would it be possible to change the text in column2 where it says "ABC" to "XYZ". Please note that there are multiple tables on the page, but I would like to replace the text for all the tables in column 2 where text = "ABC" with the new text "XYZ".

<table width="100%" class="mytable"><tbody>
    <tr><th width="70%">Column1</th><th width="30%">Column2r</th></tr>
    <tr><td>Test</td><td>ABC</td></tr>
    <tr><td>123</td><td>LMN</td></tr>
</tbody></table>
      
<table width="100%" class="mytable"><tbody>
    <tr><th width="70%">Column1</th><th width="30%">Column2r</th></tr>
    <tr><td>ppp</td><td>ssd</td></tr>
    <tr><td>dffd</td><td>ABC</td></tr>
</tbody></table>
1
  • Sure, iterate over all tables, read the cell and replace if content matches "ABC" Commented Aug 22, 2022 at 15:25

1 Answer 1

3

You can use a CSS selector to select all TD elements that occur in a second column (i.e. they are the second child in their parent element):

for (const td of document.querySelectorAll("tr>td:nth-child(2)")) {
    if (td.textContent == "ABC") td.textContent = "XYZ";
}
<table width="100%" class="mytable"><tbody>
    <tr><th width="70%">Column1</th><th width="30%">Column2r</th></tr>
    <tr><td>Test</td><td>ABC</td></tr>
    <tr><td>123</td><td>LMN</td></tr>
</tbody></table>
      
<table width="100%" class="mytable"><tbody>
    <tr><th width="70%">Column1</th><th width="30%">Column2r</th></tr>
    <tr><td>ppp</td><td>ssd</td></tr>
    <tr><td>dffd</td><td>ABC</td></tr>
</tbody></table>

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, I have more than one table on the page and want to replace the text for all the tables in column2 where text = ABC with new text XYZ.
OK, @magicsinger, thanks for clarifying. I think this answer does the job then.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.