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!
$(".myClass").text().split("<br />")[0];
$(".myClass").html().split("<br />")[0];
Referrence correction comment: @box9
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With