Home > Software design >  How to shorten a column data of a table and add dots after a specific limit using javascript
How to shorten a column data of a table and add dots after a specific limit using javascript

Time:11-03

I have a table

<table>
<tr>
    <td class="title"> Lorem ipsum dolor sit amet consectecons sit amet consectecons </td>
    <td>Lorem ipsum dolor sit amet consectecons sit amet consecteconsLorem ipsum dolor sit amet consectecons sit amet consectecons</td>
    <td>Lorem ipsum dolor</td>
    <td>Lorem ipsum dolor</td>
</tr>
<tr>
    <td class="title"> Lorem ipsum dolor sit amet consectecons sit amet consectecons </td>
    <td>Lorem ipsum dolor sit amet consectecons sit amet consecteconsLorem ipsum dolor sit amet consectecons sit amet consectecons</td>
    <td>Lorem ipsum dolor</td>
    <td>Lorem ipsum dolor</td>
</tr>
<tr>
    <td class="title"> Lorem ipsum dolor sit amet consectecons sit amet consectecons </td>
    <td>Lorem ipsum dolor sit amet consectecons sit amet consecteconsLorem ipsum dolor sit amet consectecons sit amet consectecons</td>
    <td>Lorem ipsum dolor</td>
    <td>Lorem ipsum dolor</td>
</tr>
</table>

now take class title i want to trim the data of title class and add (...) after a specific length using javascript there can be multiple <td> Help me

CodePudding user response:

const titles = document.querySelectorAll('.title');
const titleLength = 15;
titles.forEach(el => {
  el.innerText = `${el.innerText.substring(0, titleLength)}...`;
})

explanation: substring.

CodePudding user response:

Fetch the columns by class and substring the data and set it back.

const tds = document.querySelectorAll('td.title')
const length = 10;
tds.forEach((e) => {
  e.innerText = e.innerText.substring(0, length)   '...';
})
<table border="1">
<tr>
    <td class="title"> Lorem ipsum dolor sit amet consectecons sit amet consectecons </td>
    <td>Lorem ipsum dolor sit amet consectecons sit amet consecteconsLorem ipsum dolor sit amet consectecons sit amet consectecons</td>
    <td>Lorem ipsum dolor</td>
    <td>Lorem ipsum dolor</td>
</tr>
<tr>
    <td class="title"> Lorem ipsum dolor sit amet consectecons sit amet consectecons </td>
    <td>Lorem ipsum dolor sit amet consectecons sit amet consecteconsLorem ipsum dolor sit amet consectecons sit amet consectecons</td>
    <td>Lorem ipsum dolor</td>
    <td>Lorem ipsum dolor</td>
</tr>
<tr>
    <td class="title"> Lorem ipsum dolor sit amet consectecons sit amet consectecons </td>
    <td>Lorem ipsum dolor sit amet consectecons sit amet consecteconsLorem ipsum dolor sit amet consectecons sit amet consectecons</td>
    <td>Lorem ipsum dolor</td>
    <td>Lorem ipsum dolor</td>
</tr>
</table>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related