开发者

How to detect meta tag using jQuery in HTML, DOM

Here is a problem I met using a PHP script to grab an HTML page and return the HTML content as a string to jQuery's AJAX call.

$.ajax({
type: "POST",
    data: "url="+tar_url,
    url: "curl.php",
    success: function (data, textStatus, jqXHR){
       $("meta", $(data))// not working
       $(data).find("meta") //not working
       $("img",$(data)) //works
       $(data).find("div") //works                  
},

Inside the success function callback, I noticed that I could use normal selectors to get div, img, ul, etc. However, none of the above methods开发者_JAVA技巧 could select meta tags.

First, I don't know if the HTML contains any meta tags. If it contains some, I would like to select them out and parse them, etc. Is it impossible to select those meta tags with jQuery?


I had the same problem just now and came across this post while looking for a solution. In the end, what worked for me was to use filter( ) instead of find( ).

From Chrome's Javascript Console:

$.ajax({
    type: 'GET', 
    url: $getThisURL, 
    success: function(data) { output = $(data).filter('meta'); }
});

Output:

[<meta http-equiv=​"Content-Type" content=​"text/​html;​charset=utf-8">​,
<meta name=​"color:​Background" content=​"#262626">​,
<meta name=​"color:​Text" content=​"#fff">​,
<meta name=​"color:​Links" content=​"#ffbc00">​,
<meta name=​"if:​Show notes" content=​"1">​,
<meta name=​"robots" content=​"noindex">​,
<meta charset=​"utf-8">​,
<meta http-equiv=​"x-dns-prefetch-control" content=​"off">​]


you need to try something like this

var author = $('meta[name=author]').attr("content");

some other examples

$("meta[property=og:title]").attr("content", document.title);
$("meta[property=og:url]").attr("content", location.toString());

one more example from google only

var mt = $('meta[name=some-name]');
mt = mt.length ? mt : $('<meta name="some-name" />').appendTo('head');
mt.attr('content', 'some value');


When accessing facebook meta tags: If you get

"uncaught exception: Syntax error, unrecognized expression: [property=fb:app_id]"

You need to quote the property name of FB meta tags:

myApp2 = $('meta[property="fb:app_id"]').attr("content") ;


You need to use javascript escape function to post HTML tags in jquery, use this to select meta tag

escape( $(data).find("meta") )
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜