Get text before first <br/">
I am learning jQuery but a bit confused about this. I have the following HTML:
... <h1 class="myClass">First Part<br />Second Part</h1> ... I can extract this element from the downloaded data using:
$(data).find("h1.myClass"); What I want to extract is the "First Part" bit. I suggested that I could do this:
$(data).find("h1.myClass:first-child").text(); However, this results in an empty string. After a long search, I'm still not sure what I'm doing wrong here. Any help would be greatly appreciated.
Thanks!
Using plain old JavaScript and the DOM, as soon as you have an H1 dom object, you can simply call myH1.firstChild and return the node text to the next element (which you can call βdataβ to get a text string). For instance:
<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" Keep in mind that jQuery is powerful and often super-duper-efficient, but the DOM itself also provides good functionality.