April 2, 2012

extracting text from html file

Question by zeacuss

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 the
divand 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.

Answer by Starx

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
});

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!