JQuery: Adding space between multiple selections
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" i开发者_如何学编程nstead 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.
- http://api.jquery.com/map/
- http://api.jquery.com/get/
- http://www.w3schools.com/jsref/jsref_join.asp
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()
精彩评论