Regis Geoffrion
Regis Geoffrion

Reputation: 35

Removing headers from jquery text()

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

Upvotes: 2

Views: 2584

Answers (5)

John Keyes
John Keyes

Reputation: 5604

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.net/jkeyes/RpFjc/

Upvotes: 0

Lee
Lee

Reputation: 13542

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 

Upvotes: 2

amosrivera
amosrivera

Reputation: 26514

$("#mycenter *").not("h2").text()

OR

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

Demo: http://jsfiddle.net/Wer58/

Upvotes: 2

megakorre
megakorre

Reputation: 2223

Hej Regis

http://jsfiddle.net/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

Upvotes: 3

Deets McGeets
Deets McGeets

Reputation: 6387

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.

Upvotes: 3

Related Questions