Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 944
Harry Avatar asked Sep 11 '11 20:09

Harry


People also ask

How do I get inner text in jQuery?

The html(), text(), and val() are the most useful methods that can be utilized to get and set the inner text of HTML elements in jQuery. text() method gets and sets the content of HTML elements whereas, the html() method also sets its HTML markup. You can also invoke the val() HTML method for changing attribute values.

What is $() in jQuery?

In the first formulation listed above, jQuery() — which can also be written as $() — searches through the DOM for any elements that match the provided selector and creates a new jQuery object that references these elements: 1. $( "div.

How do you get the first line in JavaScript?

So here's how to find the first line of text inside an element if you need to manipulate it using JavaScript. blockName: findFirst const getFirstLine = el => { const text = el. innerHTML; //set the innerHTML to a character el. innerHTML = 'a'; //get the offsetheight of the single character const singleLineHeight = el.

What is $() in JavaScript?

$() The $() function is shorthand for the getElementByID method, which, as noted above, returns the ID of a specific element of an HTML DOM. It's frequently used for manipulating elements in a document. $() allows for shorter and more efficient JavaScript coding.


1 Answers

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];
like image 136
clem Avatar answered Sep 18 '22 23:09

clem