admin管理员组

文章数量:1334342

I need to get the text from a div with an id of mycenter, but I do not want the header text i.e.
<h2>This is my Title</h2>. I only want the text after the header. Additionally, sometimes the div does not contain any header.

I tried:

var pageText = $('#mycenter').text();

This correctly returns the text in the div, but this includes "This is My Title".

Any clue on how I can do this?

Thanks

I need to get the text from a div with an id of mycenter, but I do not want the header text i.e.
<h2>This is my Title</h2>. I only want the text after the header. Additionally, sometimes the div does not contain any header.

I tried:

var pageText = $('#mycenter').text();

This correctly returns the text in the div, but this includes "This is My Title".

Any clue on how I can do this?

Thanks

Share Improve this question edited Oct 1, 2011 at 2:39 Jayantha Lal Sirisena 21.4k11 gold badges73 silver badges93 bronze badges asked Oct 1, 2011 at 2:35 Regis GeoffrionRegis Geoffrion 353 silver badges7 bronze badges 0
Add a ment  | 

5 Answers 5

Reset to default 3

One solution can be

var pageClone = $('#mycenter').clone();
pageClone.find(':header').remove();
var pageText = pageClone.text();
pageClone.remove();

This very well may be inefficient but it will likely serve your needs.

Hej Regis

http://jsfiddle/buyms/

So what you can do is clone the div and remove the tags in it you dont want like this

var text = $("div").clone()
   .find("h2").remove().end()
   .text();


alert(text);

I hope this helps

Use jQuery's contents() function to fetch all child nodes including text nodes. Then filter the set however you like, and finally extract the text from the remaining set.

Given a document fragment like this:

<div id="mycenter">
    some text 1
    <h2>The header</h2>
    some text 2
    <div>other stuff</div>
    <h1>another header</h1>
</div>

Option #1 : Return only the text that is an immediate child of #mycenter, thus excluding the text of all child elements (not just h* elements):

$('#mycenter').contents().filter(function() {
  return this.nodeType == 3;
}).text();

Gives us:

some text 1
some text 2

Option #2 : Return all descendent text, except the contents of header (H1-H6) elements that are immediate children of #mycenter:

$('#mycenter').contents().not('h1,h2,h3,h4,h5,h6').text();

Gives us:

some text 1
some text 2
other stuff 
$("#mycenter *").not("h2").text()

OR

$("div :not('h2')").text() // see example below and this will make sense. 

Demo: http://jsfiddle/Wer58/

I went the regular expression route, but as you're using jQuery anyway I'd go with @Lee's solution.

var pageText = $('#mycenter').html().replace(/\<h2\>.*\<\/h2\>/, '')
        .replace( /^\s+|\s+$/g, '' );

Demo: http://jsfiddle/jkeyes/RpFjc/

本文标签: javascriptRemoving headers from jquery text()Stack Overflow