John
John

Reputation: 1751

jQuery extract span text with added character

I have one html code that looks like this:

<span class="itemprop" itemprop="name">AAA aaa</span>
<span class="itemprop" itemprop="name">BBB bbb</span>
<span class="itemprop" itemprop="name">CCC ccc</span>

i use this code to extract values from span:

$('span.itemprop').text();

But i get this from output:

AAA aaaBBB bbbCCC ccc

And need to get this:

AAA aaa BBB bbb CCC ccc

How can i get this output?

Upvotes: 1

Views: 48

Answers (1)

JYoThI
JYoThI

Reputation: 12085

1st : use each function to get the text and concatenate it like this

2nd : Extra space will removed by using trim()

 var texts="";
$('span.itemprop').each(function(){  texts+= $(this).text()+" ";  });

var texts="";
$('span.itemprop').each(function(){  texts+= $(this).text()+" ";  });
console.log(texts.length);
console.log(texts = $.trim(texts));
console.log(texts.length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="itemprop" itemprop="name">AAA aaa</span>
<span class="itemprop" itemprop="name">BBB bbb</span>
<span class="itemprop" itemprop="name">CCC ccc</span>

Upvotes: 2

Related Questions