skip to Main Content

Sorry if this question seems noob or doesnt make sense, i am very new to JS.

i have a web page like below –

<td class="main" data="chair">Chair</td>
<td class="main" data="table">Table</td>
<td class="main" data="desk">Desk</td>

I know how to select document by its ID or class name but here as you can see class name is same for all, how can i select value of Table?

I had tried using document.querySelectorAll and implemented foreach on it too but failed.

Can you let me know how it can be done.

2

Answers


  1. Use an attribute selector:

    https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors

    console.log(document.querySelector('[data="chair"]').textContent);
    <table>
    <tr>
    <td class="main" data="chair">Chair</td>
    <td class="main" data="table">Table</td>
    <td class="main" data="desk">Desk</td>
    </tr>
    </table>
    Login or Signup to reply.
  2. Can you try this code ?

    function exampleTable() {
    var getTables = document.querySelectorAll(".main"); 
    
    getTables.forEach((cell) => {
        var content = cell.textContent;
        var dataAttribute = cell.getAttribute('data');
    
        console.log(content);
        console.log(dataAttribute);
    });}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search