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);
});
});
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With