0

HI All im looking to make a function to truncate the text based on the value given in data attribute

so far i got nowhere my code below

    <p data-truncate="10">This is a paragraphasdasd asda ascevgr .</p>
<p data-truncate="30">This is a paragrap fdg  heg hasdasd asda ascevgr .</p>
<p data-truncate="12">This is a paragraphasdasd asda ascevgr .</p>
<p data-truncate="14">This is a paragr df fdg 534t34 34 aphasdasd asda ascevgr .</p>
<p data-truncate="16">This is a paragra 34t  gh jy rth phasdasd asda ascevgr .</p>
<p data-truncate="12">This is a paragr 3688 hjhj aphasdasd asda ascevgr .</p>
<p data-truncate="5">This is a paragraph  der ert rt asdasd asda ascevgr .</p>
<p data-truncate="90">This is a paragraph  der ert rt asdasd asda ascevgr .</p>
<script>
    let truncateme = document.querySelectorAll("[data-truncate]");
    truncateme.forEach(truncate);
    function turnecate(item) {
        var value = item.getAttribute('data-truncate');
        var txt = item.textContent;
        if (txt.length > value) {
            var txt1 = item.textContent.substring(0,value) + '...';
            console.log(txt1)
        }else{
            console.log(txt)
        }
        
    }


</script>
Nsevens
  • 2,588
  • 1
  • 17
  • 34
sam kh
  • 129
  • 1
  • 7
  • `data-truncate` is a string, even if you put a numeric value into it. To use it with `substring`, you'll need to [parse it into a number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt). In addition, your function name is misspelled and doesn't match what you're passing to `forEach`. – Etheryte Jun 17 '22 at 14:08
  • your code works fine when you correct the mispelling of the function declaration. `function turnecate(item) {...` should be `function truncate(item) {...`. – Dave Pritlove Jun 17 '22 at 14:11
  • I fixed the typo, problem is i can not change the text – sam kh Jun 20 '22 at 09:16

0 Answers0