I select some paragraphs inside a div:
$('#myDiv p.p1, #myDiv p.p2').text();
My problem is that I want to add space between each selection so that the output is: "paragraph1 (space) paragraph2" instead of "paragraph1paragraph2".
Any ideas?
I select some paragraphs inside a div:
$('#myDiv p.p1, #myDiv p.p2').text();
My problem is that I want to add space between each selection so that the output is: "paragraph1 (space) paragraph2" instead of "paragraph1paragraph2".
Any ideas?
You can use .map() with .get() to create an array of the separate paragraphs, then use .join(" ") to join them together with a space in between.
Try this:
var result = $('#myDiv p.p1, #myDiv p.p2').map(function() {
return $.text([this]);
// return this.innerHTML; // Alternate means of getting text
// return this.firstChild.nodeValue; // Another alternate
}).get().join(" ");
The result variable should have your paragraphs with a space separating them.
EDIT: Based on comment from @J-P, updated the text retrieval to be more efficient.
This will do the trick:
$('#myDiv p.p1, #myDiv p.p2').clone().append(' ').text()