开发者

jquery select text from between text

i want to grab the text between two tags, which is in main div, following is the example...

<div class="main_result">

so开发者_如何转开发me text....
<div>other divs</div>
<p>some other html</p>
<div class="bread_crump"></div>

text i want to grab

<b>selected category</b>
some other text and div...

</div>

obviously following example dont work, but its an idea..

var count = $('.main_result', data)
                                .find('.bread_crump')
                                .after('<span class="count_total" style="color:red">')
                                .parents('.main_result')
                                .find('.bread_crump ~ b')
                                .before('</span>')
                                .parents('.main_result').html();


var txt = $('.main_result')
          .contents() // get it's contents
          .filter(function() { //filter the result for textnodes that aren't empty (helps ie's parsing of textnodes)
             if( this.nodeType == 3 && $.trim(this.data) != "") { //get only text nodes and filter out whitespace elements
                 return true;
             }
             return false;
          }).get(1).data; // get 1 because it's your 2nd non-whitespace text node

var txt = $.trim(txt); // trim out all the new lines 'n stuff

Better, though, to wrap these elements in something you can a) find easily and b) rely on (the number of text-nodes can get iffy)


var firstNode = $(".main_result div.bread_crump").get(0)
var secondNode = $(".main_result b").get(0)
var nextToFirst = $("div.bread_crump").get(0).nextSibling;
if(nextToFirst.nodeType == 3 && nextToFirst.nextSibling == secondNode) {
  alert(nextToFirst.nodeValue);
}

Without much jQuery but using DOM.


I don't know of any way that you can select only a portion of text from a block of text without any markup around it. If there were any pattern to the text which is consistent, I would use

var text = $(".main_result").html();

And then use REGEX to pull the text after the "bread_crump" div and before the <b>

Without adding your desired text into an element which can referred to with a jQuery selector directly, it will be a dirty hack and depending on the consistency of the page layout, may or may not change from page load to page load. If you can't control the page layout, any of the other solutions provided here would be a closer step to a solution than what I provided.

If there's a pattern in the layout you can be sure is consistent, then focus on that as an anchor and reach your selection from there.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜