0

Having a piece of text, in case it is included in a HTML file, how would you get the node where its last character is with javascript? For instance, having this HTML:

<p>
    "foo "
    <span>bar</span>
    " foo bar"
</p>

and having the string "foo b", how would you make javascript to retrieve the node (and, if possible, the offset whithin that node) where the last character of the first occurrence is (in this case, the span node)?

I could use Jquery as well but, as far as I know, it wouldn't be easy, since that library doesn't handle text nodes.

davids
  • 6,259
  • 3
  • 29
  • 50

1 Answers1

0

Try this:

var str='foo b',
firstMatch = $('body > *:contains("' + str + '")').first(),
offset = firstMatch.text().trim().search(str) + str.length

console.log(firstMatch.get(),offset)
Avi
  • 155
  • 8
  • I think that that code would return the first child of body which contains the specified text (in the example case, it would return the p element, supposing it's under the body tag). Anyway, Jquery is not going to work in this case, because, as far as I know, it doesn't handle text nodes, so, if I wanted to get the node where the first occurrence of "fo" is, I would expect to receive the text node "foo ", and Jquery would probably return the p node. – davids Feb 29 '12 at 11:12
  • Sorry , I was not aware of text nodes maybe this can help you though: [link]http://stackoverflow.com/questions/298750/how-do-i-select-text-nodes-with-jquery – Avi Feb 29 '12 at 12:19