ofir
ofir

Reputation: 139

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 value 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

Upvotes: 0

Views: 7135

Answers (3)

a'r
a'r

Reputation: 36999

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'

Upvotes: 1

Brian
Brian

Reputation: 3601

$( temp_content ).find( 'h1' ).text()

That should do it. You are creating a jQuery object, finding the H1, and then getting its text.

Upvotes: 2

justkt
justkt

Reputation: 14766

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();
}

Upvotes: 2

Related Questions