Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to replace text in a table column with Javascript without any Table ID

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>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading