Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get text until first <br />

I'm learning jQuery, but am a bit stumped with this one. I have the following HTML:

...
<h1 class="myClass">First Part<br />Second Part</h1>
...

I can isolate this element from downloaded data using:

$(data).find("h1.myClass");

What I want to extract is the "First Part" bit. I assumed I could do this:

$(data).find("h1.myClass:first-child").text();

However, this results in an empty string. After doing a lot of searching, I am still unsure what I'm doing wrong here. Any help would be greatly appreciated.

Thanks!

like image 762
Michael Cooper Avatar asked Nov 29 '22 05:11

Michael Cooper


2 Answers

$(".myClass").text().split("<br />")[0];

EDIT:

$(".myClass").html().split("<br />")[0];

Referrence correction comment: @box9

like image 195
Babiker Avatar answered Dec 13 '22 12:12

Babiker


Using just plain old JavaScript and DOM, once you have the H1 dom object you can just call myH1.firstChild and that will return the text node up to the next element (on which you can call "data" to get the text string). For example:

<h1 class="myClass">This is<br/>a test</h1>
//...
var hs = document.getElementsByClassName("myClass");
hs[0].firstChild.data; // => "This is"

Or with idiomatic jQuery:

$("h1.myClass").get(0).firstChild.data; // => "This is"

Don't forget that jQuery is powerful and often super-duper-time-saving but the DOM itself provides some good functionality as well.

like image 28
maerics Avatar answered Dec 13 '22 13:12

maerics