开发者

JQuery: Adding space between multiple selections

开发者 https://www.devze.com 2023-01-06 13:05 出处:网络
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 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()
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号