PrincessBelle
PrincessBelle

Reputation: 195

How do I display dynamically filled span items separated by commas using JQuery and CSS?

I have these span elements that may or may not be filled dynamically at runtime. I need to display the span elements that are filled, with the text separated by commas. So for the HTML below, the output would look like this: 'Filled 1, Filled 2, Filled 3'.

   <div>   
        <h6>
            <span>Filled1</span>
            <span></span>
            <span>Filled 2</span>
            <span>Filled 3</span>
            <span></span>
        </h6>
   </div>

I tried to do this by selecting the non-empty span items and adding them to an array using JQuery, but it didnt seem to work. How can I do this? Please help. Thank you.

Upvotes: 0

Views: 1188

Answers (3)

ianaya89
ianaya89

Reputation: 4233

You can do it easy with jQuery, try something like this:

[This code was updated to replace the last comma for the 'and' word]

$(function(){
  var texts = [];

  $('span').each(function(){
    if($(this).text()) texts.push($(this).text());
  });

  var result = texts.join(', ');
  var lastComma = result.lastIndexOf(',');

  result = result.substring(0, lastComma) + ' and' + result.substring(lastComma + 1);

  alert(result);
})

Look at this codepen.

Just replace the alert for whatever you want to do with the results

Upvotes: 0

Billy
Billy

Reputation: 2448

Try this, pure css ## Edited as the way I had it left a comma at the end if there was a empty last span ##

span:not(:first-of-type):before {content:", ";}
span:empty:before{content:"";}
<h3>
  <span>filled 1</span>
  <span>filled 2</span>
  <span></span>
  <span>filled 3</span>
  <span>filled 4</span>
  <span></span>
 </h3>

Upvotes: 2

David
David

Reputation: 4873

Scan for empty nodes, and if it is not empty, add the comma

var spans = document.getElementsByTagName('h6')[0].getElementsByTagName('span');

for (var i = 0; i < spans.length; ++i) {
  if (spans[i].innerHTML != '' && (i + 2) < (spans.length)) {
    spans[i].innerHTML += ', ';
  }
}
<div>
  <h6>
        <span>Filled1</span>
        <span></span>
        <span>Filled 2</span>
        <span>Filled 3</span>
        <span></span>
    </h6>
</div>

Upvotes: 0

Related Questions