I am learning jQuery but a bit confused about this. I have the following HTML: ...

First Part

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!

+4
source share
5 answers

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

EDIT:

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

Link Correction Comment: @ box9

+7
source

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.

+5
source

To get a little more "jQuery-ish":

 $("h1.myClass").contents().eq(0).text(); 
+5
source

why not use some regex for this

 var content = $(data).find("h1.myClass:first-child").html(); var filteredContent = /(.*)<br \/>/.exec(content)[0]; 
+1
source

The "first part" is not a child, because it is not in its own element.

You can get the first part by dividing the contents of <h1 class="myClass"> by <br /> :

 var firstPart = $("h1.myClass").html().split('<br />')[0]; alert(firstPart); 

^ which will warn the "First part" :)

+1
source

Source: https://habr.com/ru/post/1332309/


All Articles