问题
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