简体   繁体   中英

jQuery get part of innerhtml

I need to get the html of ap tag, however there is a br tag inside of it. So it looks like:

<p>
    Some Text
    <br>
    Some More Text
</p>

I need to get the first part and second part separately. So I could do something like:

$('p').html() //Up To '<'
$('p').html() //After '>'

Is it possible?

If you know that there's always going to be a <br> tag, then yes. Otherwise you can utilize regex.

var foo = $('p').html().split('<br>')[0];
var bar = $('p').html().split('<br>')[1];

Try to use .contents() to retrieve the nodes that are present inside,

$('p').contents()[0].nodeValue;
$('p').contents()[2].nodeValue;

And node object has a property called nodeValue , it will give you the text that you need.

DEMO

I can suggest you two options:

First: Using substring ( FIDDLE )

var content = $('p').html();
var firstPart = content.substring(0,content.indexOf("<br>"));
var secondPart = content.substring(content.indexOf("<br>") + 4,content.length);

Second: Using split ( FIDDLE )

var content = $('p').html().split("<br>");
var firstPart = content[0];
var secondPart = content[1];

Yes, it's possible!!! use the split function...

$('p').html().split("<br>")[0];
$('p').html().split("<br>")[1];
$(document).ready(function(){

   var str = $('p').html();

   console.log(str.split('<br>'));

});

You can use the jQuery split method to split the content at the <br> tag. Then grab everything up to that.

var text = $('p').html();
text.split('<br>')[0];
text.split('<br>')[1];

To get the second part, you use the same split method but grab everything after the
tag.

Here is a link to MDN further explaining the split() method.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM