zeacuss
zeacuss

Reputation: 2623

extracting text from html file

I'm trying to get nodes containing text from html file using Javascript and jQuery. if I have a node like `

<div>txt0
<span>txt1</span>
txt2
</div>

How can I select elements that meets this criteria?? Meaning, I need to retrieve thedivand thespan` , and it would be even better to know location of the text.

I'm trying to get the text to replace it with images in a later function. I tried this

`

$('*').each(function(indx, elm){
   var txt = $(elm).text();
   // my code to replace text with images here
});

`

but it does not get the required results.. it does all the parsing in the first element, and changes the html totally.

Upvotes: 0

Views: 105

Answers (2)

Starx
Starx

Reputation: 79031

Your markup structure is a bit uneasy. Consider changing to something like this

   <div>
     <span>txt0</span>
     <span>txt1</span>
     <span>txt2</span>
   </div>

Then using jQuery

$("div span").each(function(k,v) {
   $(this).html("<img src=\""+v+".jpg\" />"); //replace with the image
});

Upvotes: 0

aaaidan
aaaidan

Reputation: 7336

I don't know exactly what you're trying to solve, but perhaps you can be a bit more specific with your selector?

$("div span").text(); // returns 'txt1'
$("div").text();      // returns 'txt0txt1txt2'

By adding ids and/or classes to your html, you can be very specific:

<div class="name">Aidan <span class="middlename">Geoffrey</span> Fraser</div>

...

// returns all spans with class
// "middlename" inside divs with class "name"
$("div.name span.middlename").text(); 

// returns the first span with class
// "middlename" inside the fourth div 
// with class "name"
$("div.name[3] span.middlename[0]").text(); 

JQuery has pretty good documentation of these selectors.

If this doesn't help, consider explaining the problem you're trying to solve.

Upvotes: 1

Related Questions