Harry
Harry

Reputation: 54949

getting the first line of text in an element jquery

I have an example element like this:

<div id="element">
  Blah blah blah.
  <div>Header</div>
  ...
</div>

it can also look like this:

<div id="element">
  <span>Blah blah blah.</span>
  <h4>Header</h4>
  ...
</div>

I want to get the first line (defining line loosely) (Blah blah blah.) of text inside the element. It might be wrapped inside a child element or just be naked textnode. How do I do that? Thanks.

Upvotes: 12

Views: 21991

Answers (5)

Mo D Genesis
Mo D Genesis

Reputation: 6149

the counter starts at 1

myElement.text().split('\n')[1]

Upvotes: 1

user113716
user113716

Reputation: 322492

Use the contents()[docs] method to get all children, including text nodes, filter out any empty (or whitespace only) nodes, then grab the first of the set.

var first_line = $("#element")
                       .contents()
                       .filter(function() { 
                           return !!$.trim( this.innerHTML || this.data ); 
                       })
                       .first();

text node: http://jsfiddle.net/Yftnh/

element: http://jsfiddle.net/Yftnh/1/

Upvotes: 16

Maximilian Hils
Maximilian Hils

Reputation: 6770

var myElement = $("#element");
while(myElement.children().length > 0)
{
   myElement = myElement.children().first();
}
var firstText = myElement.text();

Assuming that the text is correctly wrapped inside an element, of course. You might check whether there's text before the first element:

/\s*</.test(myElement.html())

Upvotes: 2

simoncereska
simoncereska

Reputation: 3043

Here is idea for you. Of course if there is h4 element before line you want to get:

var content = $('#element').html();
var arr = content.split('<h4>');
console.log(arr[0]);

Upvotes: 3

clem
clem

Reputation: 3366

first get the content of the element

var content = $('#element').html();

then split the text into an array using line break

tmp = content.split("\n");

the first part of the array is the first line of the element

var firstLine = tmp[0];

Upvotes: 1

Related Questions