views:

671

answers:

2

I have text stored in a variable which contains several span tags.
I want to get all the contents inside every span at once. How can I do that with jQuery or javascript?

<htmlText>
    Researchthe university has been given a 5 star rating in the current Research Assessment Exercise. It is one of the UK's leading technological universities, specialising in research to provide solutions critical to industry, commerce and the healthcare, voluntary and public sectors.
    <span class="NBResult"></span><span class="NBResult">Data transmission speed</span>
    <span>, green fuels,small business marketing needs, European bureaucracy and the treatment </span>
    <span class="NBSearchTerm">of</span>
    <span> </span><span class="NBSearchTerm">cancer</span>
    <span> are all under investigation at the university. </span>
</htmlText>
+4  A: 

Update: This solution has been updated following additional questions in the comments:

Just grab the .text() property of the parent selector.

var myWords = "<span>I</span><span> </span><span>like</span><span> </span><span>words.</span>";

/* "I like words" */
alert($(myWords).find("span").text());
alert($("p.words span").text());

<p class="words">
  <span>I</span><span> </span><span>like</span><span> </span><span>words.</span>
</p>
Jonathan Sampson
i have these text inside a vriable.... how can i select from it???
Jasim
Place the variable within your selector. I'll update the code...
Jonathan Sampson
but there is also some content outside the span.. i want to select only things inside span...
Jasim
Answer has been updated.
Jonathan Sampson
what if I want to select all the contents inside the span along with the span tag????
Jasim
Goodness, man :) If you want the span tags too, then you should switch from .text() to .html()
Jonathan Sampson
$("p.words").html(), and $(myWords).html()
Jonathan Sampson
A: 

If I understand correctly form the comments to Jonathan's answer, with the follwoing HTML (stored in a variable):

<div id='bla'>
    ASD
    <span>foo</span>
    sdf
    <span class='x'>bar</span>
</div>

You want to get:

<span>foo</span><span class='x'>bar</span>

You could do that using:

var htmlStuff = '<div id="bla">etc.</div>'; //the HTML
var ret = new Array();
$(htmlStuff).find('#bla').children('span').each(function(){
     var x = $(this).wrap('<div></div>').parent().html();
     ret.push(x);
});
var spanString = x.join('');

This is however kinda ugly, and wont work correctly when doing this in the DOM because you would wrap all your span's in divs. (To make this work in the DOM get the HTML of div#bla and then use that as htmlStuff)

Pim Jager