Home > Software design >  Check if td element have certain value
Check if td element have certain value

Time:11-22

i have a table with number :

<td id="table-number">{{ $loop->index   1 }}</td>

now i want to get the number of "9" from the table row

Here is what i do :

const number = document.getElementById('table-number');


if(number.textContent.includes('9')) {
            console.log('heyhey');
        }

but it returns nothing. So, what should i do? I expect to get the table number.

ok guys, i got the answer at this post, sorry i didnt serach thoroughly. Need to upgrade my google skils

CodePudding user response:

Assuming the <td> elements are produced in a loop and you want to know if any of them contain a 9, give the elements a class instead of id...

<td >

and try something like this instead

const tableNumbers = Array.from(
  document.querySelectorAll(".table-number"),
  ({ textContent }) => textContent
);

if (tableNumbers.some((content) => content.includes("9"))) {
  console.log("heyhey");
}

CodePudding user response:

You probably don't need an id or a class on the cells.

Use querySelectorAll to get a node list of all of the cells, coerce the node list to an array, and then find the cell with the text content that includes your query.

// Cache all the cells
const cells = document.querySelectorAll('td');

// Coerce the node list to an array on which you can
// use the `find` method to find the cell with the matching
// text
const found = [...cells].find(cell => {
  return cell.textContent.includes(3);
});

if (found) console.log(found.textContent);
<table>
  <tbody>
    <tr>
      <td>Cell 1</td>
      <td>Cell 2</td>
    </tr>
    <tr>
      <td>Cell 3</td>
      <td>Cell 4</td>
    </tr>
  </tbody>
</table>

  • Related