3

Using jQuery, I'm trying to get some text that lives in a remote HTML file.

I'm using filter() with a class of 'copy' to specify which text in the remote file I want to get.

This is my code:

$.get('/article.html', function(data) {

    console.log($(data).filter('.copy').text());

});

This seems to work if the element with the class "copy" has no parent. However, if the element has a parent I am unable to get the text. Why is that? And is there a way to filter the response if the element has a parent?

Michael Lynch
  • 2,682
  • 3
  • 31
  • 59

1 Answers1

5

Do it the same way jquery does with .load:

$.get('/article.html', function(data) {

    console.log( $("<div>").html(data).find(".copy").text() );

});

or even

$("#myEl").load("/article.html .copy");
Kevin B
  • 94,570
  • 16
  • 163
  • 180
  • This works. Thank you! Out of curiosity, why do you begin with $("
    ")? What does that do? Also, is there any way to use load() without actually inserting the response on the DOM? Perhaps you'd want to modify the text before doing something with it.
    – Michael Lynch Mar 12 '14 at 19:51
  • Nope, if you want to modify it, you'll want to use `$.get`. `$("
    ")` creates a div. My code creates a div, appends the response to it, then finds the desired element. since the selected element is a parent of all html in `data`, we can be sure that .find will find it.
    – Kevin B Mar 12 '14 at 19:52
  • Ok cool. Thanks for clarifying. But why can't you use $(data).find('.copy').text()? – Michael Lynch Mar 12 '14 at 19:56
  • because $(data) may result in
    being a top level element. If it's a top level element, .find will try to search within it.
    – Kevin B Mar 12 '14 at 19:56