Home > Software design >  How can I hide everything after the nth delimiter in an HTML element using CSS? [duplicate]
How can I hide everything after the nth delimiter in an HTML element using CSS? [duplicate]

Time:09-30

I have an HTML element which contains a list of synonyms. I only want the first 5 synonyms to be displayed.

I.e. for the example shown below, how can I use CSS to hide everything after and including the 5th comma for each element with the "synonyms" class?

Example:

<div class="synonyms"> talkative, garrulous, voluble, over-talkative, long-winded, wordy, verbose </div>

CodePudding user response:

This cannot be done with CSS, but you can use JavaScript to replace the textContent of those elements.

document.querySelectorAll('.synonyms').forEach(d => {
  d.textContent = d.textContent.split(", ").slice(0, 5).join(", ");
});
<div class="synonyms"> talkative, garrulous, voluble, over-talkative, long-winded, wordy, verbose </div>

  • Related