macsig macsig - 12 days ago 5
Javascript Question

Add separator between elements

I'm adding some links within a div by looping through a set of other elements.

The code looks basically like

$('.js-section').children().each(function() {
var initial = $(this).data('initial');
$(".js-section-navigation").append("<a href='#"+ initial +"'>"+ initial +"</a>" )
});


That produces something like
abcd


Now, how can I add between the characters a separator such as
|
in order to get
a | b | c | d
?

If I simply add the separator at in the append, I end up with
a | b | c | d |
but I don't want the separator after the last character.

Thanks.

Answer

Firstly your code has mis-matched quotes, although I assume this is just a typo in the question as your code would not work at all in its current state.

To fix your problem you could push() each <a> element in to an array, then join() them together with the separator when you append(), like this:

var els = [];
$('.js-section').children().each(function() {
    var initial = $(this).data('initial');
    els.push('<a href="#"' + initial + '">' + initial + '</a>');
}); 
$(".js-section-navigation").append(els.join(' | '));

Alternatively you can use the code you currently are and place the divider using CSS, something like this:

.js-section-navigation a {
    display: inline-block; 
    border-right: 1px solid #000; /* amend as needed */
    padding-right: 10px;
    margin-right: 10px;
}
.js-section-navigation a:last-child {
    border: 0;
    padding: 0;
    margin: 0;
}

Working Example

Comments