Concatenate the attached lines and remove the last character
I have a list in which I want to get all the elements and add them to a paragraph. I am currently doing this successfully, but it is not appended to one line (you need to check the DOM to see it), but somewhat instead. I tried using .concat () to fetch a new p, but it returns an error. Also when adding I add a comma to separate the items and you need to remove the last one. I am using .slice (0, -1) for this, but since they are all separate lines, this does not work.
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);
});
});
source to share
The reason it didn't work before is the access to the text you need to use text()
and you need to do it after iterating
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 the array and concatenate 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>
source to share
try it
$(document).ready(function() {
var item = $('ul li');
var p = $('p');
var total = item.length;
item.each(function(index) {
itemText = $(this).text();
if(index === total - 1) {
p.append(itemText);
} else {
p.append(itemText + ", ");
}
});
});
Riddle here http://jsfiddle.net/96t0yb6d/2/
Or modified version above
$(document).ready(function() {
var item = $('ul li');
var p = $('p');
var total = item.length;
var seperator = ", ";
item.each(function(index) {
itemText = $(this).text();
if(index === total - 1) {
seperator = "";
}
p.append(itemText + seperator);
});
});
source to share