Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 772
user268451 Avatar asked Jan 20 '23 15:01

user268451


2 Answers

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">​]
like image 133
John Heinnickel Avatar answered Jan 30 '23 20:01

John Heinnickel


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');
like image 30
kobe Avatar answered Jan 30 '23 22:01

kobe