How to add a comma using css, if there are more elements after it? Items are added dynamically.

The markup is as follows:

<span class="tags-list "> <a href="#">элемент1</a> <a href="#">элемент2</a> <a href="#">элемент3</a> </span> 

Initially it is not known how many elements will be displayed, one or several.

  • Items are added dynamically. What means does this happen: javascript ? - Bald
  • yes, loaded via ajax - Marina Voronova
  • 3
    @MarinaVoronova then can the logic of the output there and organize? via css will be .tags-list a:not(:last-child):after { content: ','; } .tags-list a:not(:last-child):after { content: ','; } ........ but with dynamic addition it’s not a fact that it will turn out - Alexey Shimansky
  • those. From the server comes an array of elements that you want to display separated by commas? - Bald
  • if I understand correctly, then yes - Marina Voronova

2 answers 2

So that the question did not go unanswered, did the following:

 .tagswidget { font-size: 20px; margin-bottom: 10px; } .tagswidget .tags-list { display: inline-block; width: 85%; } .tags-list a { text-decoration: none; } .tags-list a:not(:last-child):after { content: ', '; margin-right: 10px; } 
 <div class="tagswidget"> <div class="tags-list"> <a href="#">text</a> <a href="#">text</a> <a href="#">text</a> </div> </div> 

    Gets all but the last element through

     Array.prototype.slice.call(elements, 0, -1) 

    Thus, it is not necessary to create an extra array from a NodeList to perform slice .

    Further, through forEach resulting array elementsWithoutLast retrieved and a comma is added to the end for each element: i.textContent += ',' .

     const elements = document.querySelectorAll('.tags-list a') const elementsWithoutLast = Array.prototype.slice.call(elements, 0, -1) elementsWithoutLast.forEach(i => i.textContent += ',') 
     <div class="tags-list"> <a href="#">foo</a> <a href="#">bar</a> <a href="#">baz</a> </div>