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>
div
How can I select elements that meets this criteria??
Meaning, I need to retrieve theand the
span` , 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
});