tags:

views:

73

answers:

2

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?

+6  A: 

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.

patrick dw
+1, although I think `$.text([this])` will be a bit faster than constructing a new jQ object with `$(this)`...
J-P
@J-P: Good point. I'll update. :o)
patrick dw
+1, Fastest solution.
Gert G
A: 

This will do the trick:

$('#myDiv p.p1, #myDiv p.p2').clone().append(' ').text()
Gert G
what is that? accepted but rated -1 ?!?!
Thariama
What is wrong with this solution since someone voted it down? Its much simpler then patricks.
HelpMe
Gert - While I didn't down vote you (I don't like to do that against competing answers), I imagine it is because you are making unnecessary DOM modifications, and DOM modifications are slow.
patrick dw
@Thariama, @Gert - Just did a quick test (in Firefox only) comparing the two in a loop of 1000 iterations. DOM modification took around 2,200 ms, mine took around 100 ms. Avoid the DOM when you can. :o)
patrick dw
point taken. Thanks again
HelpMe
@patrick - I appreciate your feedback. I guess `$('#myDiv p.p1, #myDiv p.p2').clone().append(' ').text()` would have been better. Not sure how speedy the `clone()` function is though.
Gert G
Gert - Using `.clone()` provided a massive improvement. Brought it down to around 190 ms! Still not quite as fast, but *much* better.
patrick dw
@patrick - Yes, you're right. Shorter code isn't always better or faster... :D Thanks again for the feedback.
Gert G
Gert - You're welcome. :o) +1 on your corrected answer.
patrick dw