How to get a text before given element using jQuery?

前端 未结 4 1394
鱼传尺愫
鱼传尺愫 2020-12-17 14:59

Let\'s consider following html code:

Some text followed by a span element and another text followed by a bold

4条回答
  •  余生分开走
    2020-12-17 15:37

    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:

    • The previousSibling property
    • jQuery.map

提交回复
热议问题