tags:

views:

36

answers:

3
<cite>
    text here...
    <a id="target_element"></a>
</cite>

How to get the text before #target_element?

+2  A: 

This isn't the prettiest solution but it will work in that specific case:

$('#target_element').parent().text();

It is best to put that text in another element, like a span. Otherwise, that text can get messed up really easily. If it was in a span, you could do something like:

$('#target_element').prev().text();

That way you will run into less errors.


EDIT

I found another way:

var elementClone = $('#target_element').clone();
elementClone.children().remove();
elementClone.text();
Kerry
Is there a general solution for this?
wamp
but this will also get the text of `<a>`... I'm not sure if the OP needs that...
Reigel
oh no,I don't want the text of `<a>`, sorry @Kerry, I can't change the html structure.
wamp
See my updated answer -- I know of no way to get text without the other elements
Kerry
Found a way to do it
Kerry
A: 

at first time make a place for replacement:

<div id="target"></div>
<a id="target_element"></a>
klox
+2  A: 
$("#target_element").parent().contents().filter(function(){ 
       return this.nodeType == 3; 
}).text();

demo

Reigel