Include "clickable" commas among various <span> elements

Struggling to insert commas between a series of items? Well, fear not!

If you're wondering how, it can be achieved with a simple line of code:

.comma:not(:last-of-type)::after{
    content: ", ";
}
<span class="comma">A</span>
<span class="comma">B</span>
<span class="comma">C</span>

However, there's a catch - the commas are not visible text that can be selected. So, if you need them selectable for copying purposes, is there a way to make this happen using CSS or JavaScript?

Let's put our heads together and come up with a solution!

Answer №1

To accomplish this task, you can utilize the document.querySelectorAll method. This will allow you to target all span elements with the class name ".comma" except for the last one. Once selected, you can then append a comma to their content using the innerText property:

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 wish to exclude commas after "empty" spans, you can verify the length of the inner text before adding 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>

In cases where the spans may contain whitespace that should be disregarded, remember to trim the values before proceeding:

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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Angular 4 to delete selected rows based on user input in typescript

I am facing a challenge with a table that contains rows and checkboxes. There is one main checkbox in the header along with multiple checkboxes for each row. I am now searching for a function that can delete rows from the table when a delete button is clic ...

Spacing between hidden checkboxes and their labels

I've customized some checkboxes to resemble a select dropdown by hiding the input and using only the label as the visible element. However, I'm struggling to add margin between the elements, which seems to work only when the checkbox is visible. ...

The side modal features a full-height design with headers, bodies, and footers that are

I have created a side modal that extends to full height. The content in the modal body is quite lengthy, but I am facing an issue where the header, body, and footer are not equal in size. I am considering using scrollspy on the HTML body tag to potentially ...

Split Screen Text Comparisons

For some reason, I am finding it challenging to display two paragraphs side by side without disrupting the overall layout. If you would like a visual explanation of the issue, please check out this video: Video If you're interested in reviewing the c ...

After the ajax call has finished loading the page, I would like to toggle a particular div

When I trigger a click event on an element, it calls a function with Ajax calls. How can I toggle a div (which will be loaded after the Ajax call) once the page is loaded? function triggerFunction(){ $("#trigger_div").trigger("click"); $("#to ...

Is there a way to prevent the "undefined" message from displaying in the console when this code is run?

Help needed! Can someone assist me in resolving the issue where the word 'undefined' is being displayed in the console? I'm a beginner in programming and struggling with this. Here's what I'm currently seeing: You are not getti ...

Issue with EJS template displaying no information

I am encountering an issue with ejs templates. While I have successfully used it in a previous project, in my current one, it's not working as intended. Instead of rendering the cards with the passed data, all I see is a blank page. Here is my code fo ...

Is there a way for me to make the login button redirect to the Dashboard?

I'm currently working on a piece of code where I need to implement some form of validation when the user clicks on the sign-in button. Specifically, I want to ensure that both the username and password fields are not left empty. If this condition is m ...

Absolute positioning causes a 100% height container to be displaced from the IE viewport

While my code works seamlessly in Firefox and Safari, Internet Explorer presents a challenge I cannot seem to solve. The Problem: In non-IE browsers, the container displays properly with space around the edges of the viewport. However, in IE, the containe ...

A Vue computed property is returning the entire function instead of the expected value

One of my computed properties is set up like this: methods: { url_refresh: function (id) { return `${this.url_base}?start=${Date.now()}` } } However, when I attempt to print the value on mount: mounted() { console.log(this.url_refresh) ...

What techniques can I use to streamline this jQuery script?

Presented below is the code for a straightforward newsletter signup widget. I believe there's potential to streamline it further, any suggestions? const emailForm = $('.widget_subscribe form'); const emailSubmit = $('.widget_subscrib ...

What is the best way to maintain two distinct background effects that each require different pixel sizes?

I am attempting to create a gradient that goes from the top-right corner to the bottom-left corner, and I also want to add a grid of dots. However, the method I am using to create the grid of dots is through a radial gradient which requires a small backgro ...

Disappearing Div Dilemma: The Mystery of the Responsive Design

I am currently facing an issue where two div elements (`.left` and `.right`) are not displayed vertically when the width value is less than 800px. Strangely, the `.left` div disappears when I try to adjust the width. I have shortened the code for clarity. ...

Transforming Django models into JSON format to be utilized as a JavaScript object

Looking to retrieve model data as an object in Javascript, I've been using the following approach in my Django view: var data = {{ data|safe }}; Here is how my view is set up: context = { 'data': { 'model1': serializ ...

How can I slow down the response time in Express Node?

I have set up a route that triggers an asynchronous function when the URL is accessed. This function will eventually return a value, which I want to use as the response for the get request. However, I am facing an issue with delaying the response until the ...

Ways to retrieve the value of a specific key within an object nested within another object

Suppose I have a variable named x with the following structure: x = { choice1: { choice: { name: "choice1", text: "abc", key: "key1" } isChecked: true }, choice2: { choice: { name ...

What steps should I take to create this animation?

So here's my concept: I envision a circle div positioned in the center with multiple small lines extending outwards, resembling rays of sunlight. How should I go about achieving this effect? Would implementing JavaScript or utilizing CSS3 animations b ...

Using AngularJS to interact with resources by passing in the scope parameter

My issue is as follows: I am attempting to call a resource with a specific parameter, but I keep encountering the following error: [$resource:badcfg] I have spent the last 3 hours trying to resolve this, but to no avail. When I call the resource like th ...

Creating a masonry layout with uniform row heights

I am trying to achieve a masonry style layout for these cards in Bootstrap. The current setup has columns with the same height, but I want them to have fluid height and consistent margin spacing like the blue line shown below. I attempted to use .card-colu ...

Using Node.js and Typescript to bring in external modules from

Attempting to generate a random integer between 1 and 6 using the 'random' library. Here's what I have coded so far: import random from 'random' function rollDice(min:number, max:number) { return Math.floor(Math.random() * (ma ...