Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Take data from a table to display as plain text

I want to take data from each row to display as simple text on the same page in a paragraph.

Example table below:

<table>
    <thead>
        <tr>
            <th class="a header">A</th>
            <th class="b header">B</th>
            <th class="c header">C</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td class="a">A1</td>
            <td class="b">B1</td>
            <td class="c">C1</td>
        </tr>
        <tr>
            <td class="a">A2</td>
            <td class="b">B2</td>
            <td class="c">C2</td>
        </tr>
    </tbody>
</table>

The output should look like:

A1 B1 C1   A2 B2 C2

I have tried look for the solution, but it is not working. I appreciate any help in advance.

like image 858
RochaCarter07 Avatar asked Dec 02 '25 05:12

RochaCarter07


1 Answers

Use document.querySelectorAll('td') to get all the td elements. Iterate over the elements using forEach loop and get their text using textContent. In the paragraph add this text using innerHTML

document.querySelector('#a').querySelectorAll('td').forEach((e)=>document.querySelector('#here').innerHTML+=e.textContent + " ")
<table id="a">
     <thead>
      <tr>
       <th class="a header">A</th>
       <th class="b header">B</th>
       <th class="c header">C</th>
      </tr>
     </thead>
     <tbody>
      <tr>
       <td class="a">A1</td>
       <td class="b">B1</td>
       <td class="c">C1</td>
      </tr>
      <tr>
       <td class="a">A2</td>
       <td class="b">B2</td>
       <td class="c">C2</td>
      </tr>
     </tbody>
   </table>
   
   <p id="here"></p>

Using jquery, get all the td elements and iterate over them using each and append the text to the paragraph using append()

$('#a').find('td').each(function(i,e){
$('#here').append($(e).text() + " ")
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="a">
     <thead>
      <tr>
       <th class="a header">A</th>
       <th class="b header">B</th>
       <th class="c header">C</th>
      </tr>
     </thead>
     <tbody>
      <tr>
       <td class="a">A1</td>
       <td class="b">B1</td>
       <td class="c">C1</td>
      </tr>
      <tr>
       <td class="a">A2</td>
       <td class="b">B2</td>
       <td class="c">C2</td>
      </tr>
     </tbody>
   </table>
   
   <p id="here"></p>
like image 60
ellipsis Avatar answered Dec 03 '25 18:12

ellipsis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!