Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate appended strings and remove last character

I have a list that I want to retrieve all items and append them to a paragraph. I am currently successful in doing so but it doesn't append into one string (you need to check the DOM to see it), but several instead. I have tried using .concat() to retrieve the new p but it returns an error. Also while appending I am adding a comma to separate the items, and need to remove the last one. I am using .slice(0, -1) to do so, but because they are all separate strings it does not work.

JSFiddle

HTML

<ul>
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
    <li>Four</li>
    <li>Five</li>
    <li>Six</li>
    <li>Seven</li>
    <li>Eight</li>
</ul>

<p>String goes here: </p>

JS/JQuery

$(document).ready(function() {
    var item = $('ul li');
    var p = $('p');

    item.each(function() {
        itemText = $(this).text();
        p.append(itemText + ", ").slice(0,-1);
    });
});
like image 227
alexmattorr Avatar asked Jan 24 '26 22:01

alexmattorr


1 Answers

The reason it wasnt working before is because to access the text you need to use text() and you need to do it after the iterations

p.text(p.text().slice(0, -2)); //notice -2 because you have an additional space ', '

$(document).ready(function() {
  var item = $('ul li');
  var p = $('p');

  item.each(function() {
    itemText = $(this).text();
    p.append(itemText + ", ")
  });
  p.text(p.text().slice(0, -2)); //notice -2 because you have an additional space ', '
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<ul>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
  <li>Four</li>
  <li>Five</li>
  <li>Six</li>
  <li>Seven</li>
  <li>Eight</li>
</ul>

<p>String goes here:</p>

However, a better approach would be to prepare an array and join at the end

$(document).ready(function() {
    var item = $('ul li');
    var p = $('p');
    var itemTextA = [];
    item.each(function() {
        itemTextA.push($(this).text());
    });
    p.append(itemTextA.join(', '));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<ul>
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
    <li>Four</li>
    <li>Five</li>
    <li>Six</li>
    <li>Seven</li>
    <li>Eight</li>
</ul>

<p>String goes here: </p>
like image 195
AmmarCSE Avatar answered Jan 26 '26 12:01

AmmarCSE