Blah blah blah.
Header
......">

Getting the first line of text in a jquery element

I have an example of such an element:

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

it might also look like this:

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

I want to get the first line (the defining line freely) (Blah blah blah.) Of the text inside the element. It can be wrapped inside a child element or just be a bare text block. How can I do it? Thanks.

+9
source share
5 answers

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

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

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

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

+16
source

Here is an idea for you. Of course, if there is an h4 element in front of the line you want to get:

 var content = $('#element').html(); var arr = content.split('<h4>'); console.log(arr[0]); 
+2
source
 var myElement = $("#element"); while(myElement.children().length > 0) { myElement = myElement.children().first(); } var firstText = myElement.text(); 

Suppose the text is correctly wrapped inside the element, of course. You can check if there is text before the first element:

 /\s*</.test(myElement.html()) 
+2
source

first get the contents 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]; 
0
source

counter starts at 1

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

All Articles