Search code examples
javascriptarraysdominnerhtml

How to return textcontent from tags in DOM in Javascript


I have the following code:

    <table>
    <tbody style="font-size: 50px;">
        <tr>
            <td style="color: #ff00ff; background-color: #ffffff;">Q</td>
            <td style="color: #442244; background-color: #442244;">Y</td>
            <td style="color: #ffff00; background-color: #442244;">A</td>
        </tr>
        <tr>
            <td style="color: #ffeefe; background-color: #990000;">Q</td>
            <td style="color: #ffff00; background-color: #ffff00;">M</td>
            <td style="color: #000000; background-color: #ff7777;">O</td>
        </tr>
    </tbody>
</table>

I have to write function in Javasript which return all letters in array. Then I have to return all letters where
color == background-color


Solution

    1. Below code returns all letters from your submitted html.
    Array.from(document.getElementsByTagName("td")).map(cell => cell.innerText)
    
    1. Below code returns all letters where their td color and bg-color values are equal.
    Array.from(document.getElementsByTagName("td")).filter(cell => cell.style.color && cell.style.backgroundColor && cell.style.color === cell.style.backgroundColor).map(cell => cell.innerText);