开发者

How to get the text before $el with jQuery?

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

How to get th开发者_C百科e text before #target_element?


$("#target_element").parent().contents().filter(function(){ 
       return this.nodeType == 3; 
}).text();

demo


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();


at first time make a place for replacement:

<div id="target"></div>
<a id="target_element"></a>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜