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.

1
  • Maybe, jQuery("[html*='foo b']") would work or at least narrows your search.
    – kirilloid
    Feb 29, 2012 at 10:22

1 Answer 1

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)
2
  • 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, 2012 at 11:12
  • Sorry , I was not aware of text nodes maybe this can help you though: [link]stackoverflow.com/questions/298750/…
    – Avi
    Feb 29, 2012 at 12:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.