Retrieving string between html tags using jQuery
I have managed to retrieve the html content of a web page via jQuery and ajax. Now I want to find the val开发者_运维技巧ue between the h1 tags and display it. How can I do it in jQuery?
$.get(link, function(res){
//get link content
var temp_content = res.responseText;
}
thank's
$( temp_content ).find( 'h1' ).text()
That should do it. You are creating a jQuery object, finding the H1, and then getting its text.
Use .find() to find where in the returned string you have <h1></h1>
and .text() to get anything between <h1></h1>
.
Note that if this webpage is on another domain you have cross-site scripting issues to deal with. If it is on the same domain you should be fine.
$.get(link, function(res){
//get link content
var temp_content = res.responseText;
$(temp_content).find("h1").text();
}
The solution depends on where the tag has been returned to you in the HTML response. For example, if the <h1>
element is in the main body or standalone in the string without the surround html and body tags, then find()
won't work for you. See this examnple:
var html_str = '<html><body><h1>Title</h1><h1>Second Title</h1></body></html>';
var html_str2 = '<h1>Title</h1><h1>Second Title</h1>';
$(html_str) --> jQuery( h1, h1 )
$(html_str2) --> jQuery( h1, h1 )
If you call find on these jQuery objects, then it will attempt to find the desired element from the children of the <h1>
elements. This of course won't work. You can use filter to ensure that you only get the desired tag or just call text()
directly, eg.
$(html_str).filter('h1').first().text() --> 'Title'
$(html_str2).first().text() --> 'Title'
If the <h1>
is wrapped in a div, then it works fine. See:
var html_str3 = '<div><h1>Title</h1><h1>Second Title</h1></div>';
$(html_str3).find('h1') --> jQuery( h1, h1 )
$(html_str3).find('h1').first().text() --> 'Title'
And lastly, remember to call first()
as otherwise you will get the text from several <h1>
elements concatenated together.
$(html_str3).find('h1').text() --> 'TitleSecond Title'
精彩评论