Jquery - Get Text Between 2 Div Tags

回眸只為那壹抹淺笑 提交于 2021-01-27 13:20:38

问题


UPDATED : Please look code below:

<div class='parent'>
    <div class='first'>whatever content</div>
    <div class='child1'></div>

    Paragraph 1
    <br>
    Paragraph 2

    <div class='child2'></div>
    <div class='child3'>whatever</div>

    i don't wanna this text

    <div class='last'>whatever</div>
</div>

How can I get text " Paragraph 1 Paragraph 2 " without text "I don't wanna this text" from that code?

Thank you.

NOTED : I CAN'T EDIT/CHANGE HTML CODE.


回答1:


1 - How to get only a content without tags:

HTML:

<div class="parent">
    <div class="first">whatever content</div>
    <div class="child1"></div>

    Paragraph 1
    <br>
    Paragraph 2

    <div class="child2"></div>
    <div class="child3">whatever</div>

    Last Content

    <div class="last">whatever</div>
</div>

JQUERY:

var content = $('.parent').clone().children().remove().end().text();
alert(content);

Demo: http://jsfiddle.net/vRbCw/3/

2- How to remove the content before div.child3:

JQUERY:

var appendSt = $('.child3').after('code:'),
    content  = $('.parent').clone().children().remove().end().text(),
    reg      = content.replace(/code:([^xyz]+)/, '');
alert(reg);

Demo : http://jsfiddle.net/sBSRH/

Get The Text Of Element Without Child Element: http://viralpatel.net/blogs/jquery-get-text-element-without-child-element/




回答2:


You should really look into doing something completely different. However, you can get text nodes by using .contents() and checking to see if the nodeType is 3.

var textNodes = $('.parent').contents().filter(function(){
  return this.nodeType === 3 && /[a-z]/g.test(this.nodeValue);
});

I'm only returning textNodes with at least one letter inside of it.

http://jsbin.com/eziqil/1/edit

You can wrap it up in a span to style it if you'd like by using .wrap() on the collection.

http://jsbin.com/eziqil/2/edit



来源:https://stackoverflow.com/questions/17982776/jquery-get-text-between-2-div-tags

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!