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 wrappe开发者_Go百科d inside a child element or just be naked textnode. How do I do that? Thanks.
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/
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]);
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())
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];
the counter starts at 1
myElement.text().split('\n')[1]
精彩评论