0

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

3 Answers 3

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

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

1

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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.