1

I have a long list of items in a list item, which I need to go through and add a comma and space and display as a comma seperated string of items:

So i have the following:

 <ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
    <li>etc</li>
 </ul>

Which I need to be display as the following:

Item 1, Item 2, Item 3, Item 4, etc

 <p>Item 1, Item 2, Item 3, Item 4, etc</p> 

I am new to javaScript so any help would be great.

Thank

6
  • 2
    Please show us the code you've written and we'll be happy to help. Commented Jul 25, 2013 at 14:11
  • do you mean by transversing the dom? or string formatting html code? please provide more info. also, are you using jquery? Commented Jul 25, 2013 at 14:13
  • Look into document.getElementsByTagName() and .innerHTML (or .textContent and .innerText), as well as a for loop. Then document.createElement() and .appendChild() (if necessary) Commented Jul 25, 2013 at 14:13
  • 1
    Here's an option: jsfiddle.net/5S6WD Commented Jul 25, 2013 at 14:20
  • 3
    This looks a lot like homework (: Commented Jul 25, 2013 at 14:20

6 Answers 6

5

Using unique ID's in your code makes work like this much simpler.

<ul id="myUL">
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
    <li>etc</li>
 </ul>
<p id="myPara"></p>

The javascript would look like this

//Grab your ul element by id and then all the li tags within it.
var myArr = document.getElementById("myUL").getElementsByTagName("li");
//Grab your paragraph you wish to populate
var para = document.getElementById("myPara");
//Specify an output array
var output = [];

//Loop over your li's and grab the html content
for(var i=0; i<myArr.length; i++){
    output.push(myArr[i].innerHTML);
}

//Set the paragraph value by joining the outputs together 
para.innerHTML = output.join(", ");

Here is a working jsFiddle - http://jsfiddle.net/GBdTM/

Some useful references

Sign up to request clarification or add additional context in comments.

4 Comments

Your code assumes the target paragraph exists in the DOM already, which I don't think is a safe assumption.
@DerekHenderson Although thats a fair point, the paragraph is included in my example and I feel i've supplied enough detail to point the user in the right direction, without coding for every eventuality.
@DerekHenderson If it were a requirement perhaps the question writer should have included that.
@VoronoiPotato & MarkWalters, fair points, which is why I didn't downvote, but usually I feel it is best to stick to the specified parameters.
3

You want to select the interesting elements, get their text and join the texts with the string ", " as the delimiter.

Get the elements with document.querySelectorAll:

var els = document.querySelectorAll("ul > li"); // ul > li is a "CSS selector"

Translate the collection of elements to a collection of their text by iterating over the returned NodeList:

var text = [];
for (var i = 0; i < els.length; ++i) {
    text.push(els[i].textContent);
}

Join them together with Array.join:

var joined = text.join(", ");

A few caveats:

  • querySelectorAll is not supported in IE < 8
  • textContent is not supported in IE < 9, but you can use innerText for old IE

2 Comments

I did something really similar in a fiddle so I'll just leave it here jsfiddle.net/Ap2bp/1
@NicoSantangelo yeah like it .children or .childNodes is probable better to use.
2

No JavaScript needed here. Some CSS will do it as well, and keep the more semantic document structure:

ul {
    display: block;
    padding: 0;
}
li {
    display: inline;
}
li:not(:last-child)::after {
    content: ", ";
}

(demo at jsfiddle.net)

3 Comments

As you know, though, this doesn't really answer the question. Yes, it is easy to style the list to appear as an inline comma-separated list, but perhaps there is some reason the OP needs the list's content copied into a paragraph.
I know, please don't downvote :-) para.textContent = _.pluck(list.children, "textContent").join(", ") just seemed too trivial…
LOL, no I have no intention of downvoting. I just wish whoever downvoted my answer would explain the reason.
1

Hope this small example will give you something to work of.

$(document).ready(function () {
        var str = '';
        $('li').each(function () {
            str += $(this).text() + ', ';
        });

        //Remove the last two character
        str = str.slice(0, -2);

        //assign the string to the <p>
        $('p').text(str);
    });

jsFiddle Example

Comments

1

You can easily get this using Jquery -

Html -

 <ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
    <li>etc</li>
 </ul>
<span id="lstItem"></span>

Jquery -

$(document).ready(function(){
    var ListItem = "";
    $('ul li').each(function(){
      ListItem += $(this).text() + ", ";    
    });

    $('#lstItem').text(ListItem.substring(0,(ListItem.length - 2)));
});

Try - Jquery Demo

Solution with Javascript -

var listli = document.getElementsByTagName("li");
var lstItem = [];
for(var i=0; i<listli.length; i++){
    lstItem.push(listli[i].innerHTML);
}
 var showlist = document.getElementById("lstItem");
 showlist.innerText = lstItem.join();

Try With Javascript

3 Comments

Why are you using jQuery for this?, it's not in the question, you're not explaining what it is, it's not really necessary and your code is more complicated that what it should be. Also, don't use uppercase variables, they will be mistaken by classes
Yes, i known the question is not related to "Jquery" but "Jquery" is a library of "Javascript", so i post my answer here to help. And Thank for your suggestion.
Sorry if I was a little harsh. A one liner that does the same thing could be: $.map($('li'), function(li){ return li.textContent; }).join(", ") );
1

Simply get the collection of LIs, concatenate their texts, and insert into a P that you create and append to the BODY:

var items = document.getElementsByTagName('li'),
    count = items.length,
    para = document.createElement('p'),
    str = items[0].innerHTML,
    i;

for (i = 1; i < count; i += 1) {
    str += ', ' + items[i].innerHTML;
}

para.innerHTML = str;
document.body.appendChild(para);

Demo

Edit: It's 2021, and there is a much better way to do this.

const items = document.querySelectorAll('li');
const stringifiedList = Array.from(items)
  .map(item => item.textContent)
  .join(', ');
const para = document.createElement('p');

para.textContent = stringifiedList;
document.body.appendChild(para);

1 Comment

Please explain the downvote. This code does precisely what the OP requested.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.