'Add "selectable" commas between multiple <span> items
I'm trying to add some commas between a list of items.
I know that you can do that by using :
.comma:not(:last-of-type)::after{
content: ", ";
}
<span class="comma">A</span>
<span class="comma">B</span>
<span class="comma">C</span>
But with this technic the commas are not really written (you can't select them). I need to be able to select them because I then copy the text in the clipboard :)
Any ideas on how to do this (with css or js) ?
Solution 1:[1]
You can use document.querySelectorAll to select all but the last .comma span, and then add a comma to their innerText:
spans = document.querySelectorAll('.comma:not(:last-of-type)')
spans.forEach(span => span.innerText = span.innerText + ', ')
<span class="comma">A</span>
<span class="comma">B</span>
<span class="comma">C</span>
If you want to avoid placing commas after "empty" spans, you could check the length of the innerText before appending a comma:
spans = document.querySelectorAll('.comma:not(:last-of-type)')
spans.forEach(span => span.innerText = span.innerText + (span.innerText.length ? ', ' : ''))
<span class="comma">A</span>
<span class="comma"></span>
<span class="comma">C</span>
And if the spans might contain whitespace that you want to ignore, just trim the values first:
spans = document.querySelectorAll('.comma:not(:last-of-type)')
spans.forEach(span => span.innerText = span.innerText.trim() + (span.innerText.trim().length ? ', ' : ''))
<span class="comma">A </span>
<span class="comma"> </span>
<span class="comma"> C</span>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
