How to get a text before given element using jQuery?

前端 未结 4 1362
鱼传尺愫
鱼传尺愫 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:19

    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?

    0 讨论(0)
  • 2020-12-17 15:30
    var textBefore = $('span')[0].previousSibling.nodeValue;
    

    I was looking for a solution to this, and was confused why I needed to map to an array. Context was not working for me. I finally figured out how to write it.

    This is the most basic solution. Putting the [0] converts the element to an elementNode, which allows you to call the previousSibling code. There's no need to put it in an array using the map function unless it is more convenient.

    0 讨论(0)
  • 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
    0 讨论(0)
  • 2020-12-17 15:45

    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.

    0 讨论(0)
提交回复
热议问题