tags:

views:

117

answers:

3

Let's consider following html code:

<p>
  Some text followed by <span>a span element</span>
  and another text followed by <b>a bold text</b>.
</p>

How can I get the text before the span and b elements using jQuery?

I tried $("span").prev() and $("b").prev() but it did work because the text is not an element. I also tried $("span").parent() but it matched whole paragraph, while I want only a part of it.

Could you advise any solution? Thank you in advance :-)

+3  A: 

I'm afraid you will need to use regular expressions for that. In order to get the text before span element use something like this:

var txt = $('span').parent().html();
var regex = /(.*)<span>/;
txt = txt.match(regex)[1];

Modify the regex to match other parts of the string as well.

RaYell
+1 you beat me to it!
Jared
This won't work because text() doesn't return any html. Secondly, even if you change it to using html(), the target element may not be the first span in the parent.
Borgar
This is just a demo how you can do it. There's no easy way to get this text stripping all tagged contents. You have to use regular expressions.
RaYell
+4  A: 

How about collecting them into an array instead of two calls to $:

var texts = $('span, b').map(function(){
    return this.previousSibling.nodeValue
});
texts[0]; // "Some text followed by "
texts[1]; // " and another text followed by "

References:

Roatin Marth
Superb answer. Well reasoned and referenced.
KyleFarris
Thank you for the solution. However, I cannot make it work in this scenario. `var c = jQuery('span');` and later `c.previousSibling` returns `null` but `c.context.previousSibling` is ok. Why?
czuk
I'm saying, don't use that scenario (`c.context`). Use the code in my answer.
Roatin Marth
A: 

I have come up with a following solution:

var c = $("span").context.previousSibling;
alert(c.data);

But I am not sure how safe it is when using different browsers?

czuk
Why don't you just use my solution? It does the same thing but without accessing `.context`.
Roatin Marth
This is an alternative solution. Your solution cannot be used (I could not) in all situations.
czuk