1

I have this which contains a string containing html of whole page. I'm running jQuery to get its meta tag and title like this

> console.log( $body.find('meta[name=description]').html() );   
> //returns null 

> console.log( $body.find('title').length );             
> //returns 0

and its not happening. Any clue?

0

2 Answers 2

1

There is no wrapper element so you need to use filter

console.log($body.filter('meta').text())
2
  • 1
    @user3586217 jQuery seems to be converting your string to HTML by creating a <div> and setting the string as its innerHTML. <html>, <head> and <body> cannot reside within a <div>, so the browser ignores them and adds only their content instead, which means $body now has a bunch of text nodes and elements that you expect to reside within the ignored elements. find looks in the descendant elements of the current element group (so, within the text nodes and the descendants of <head>, for example, <meta> and <title> and since they do not have the elements you need, find fails.
    – PhistucK
    May 2, 2014 at 14:55
  • Very elegant. Thanks. May 2, 2014 at 15:37
-1

Normally a meta tag contains an attribute with content. So the jQuery syntax would be this:

$html = $('<div>').html($body)
$('meta[name=description]', $html).attr('content')

When $body is equal $(document), $body.find('title').length should equal to 1

2
  • The original poster is not asking about the current document, but about a new document generated from a string.
    – PhistucK
    May 2, 2014 at 14:56
  • Yeah, I saw that after posting my answer. I updated the code. May 2, 2014 at 14:58

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.