- You had an extra space
? domain=
.
- Also, use
this.getAttribute("href")
or jQuery's $(this).attr("href")
- use
https
!!!
$("a[href^='http']").each(function() {
var href= this.getAttribute("href");
$(this).prepend('<img src="https://www.google.com/s2/favicons?domain='+ href +'">';
});
<li><a href="https://dribbble.com/">Dribbble</a></li>
<li><a href="https://behance.net">Behance</a></li>
<li><a href="https://www.danwebb.net">Dan Webb</a></li>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
But you'll most surely run into this error:
...has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access
so it's not possible using JS only.
PHP to the rescue:
Since the CORS policy issue in usign AJAX directly to fetch content from websites that do not allow this - you could instead:
- AJAX
GET
a PHP script on your server that will grab the external site
- now that the content is on your domain AJAX will respond with that content.
- parse the response data using JS (jQuery) to get the desired elements attribute values or text.
grabber.php
<?php
echo file_get_contents($_GET["url"]);
index.html
<ul>
<li><a href="https://dribbble.com/">Dribbble</a></li>
<li><a href="https://behance.net">Behance</a></li>
<li><a href="https://www.danwebb.net">Dan Webb</a></li>
</ul>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script>
function grabber (url, el) {
$.ajax({
url: "grabber.php?url="+ url,
type: "GET",
success: function(data){
// console.log( data );
var $head = $(data).find("head");
var title = $head.find("title").text();
var desc = $head.find("meta[name='author']").attr("content");
console.log(title , desc);
$(el).append(" - "+ title +" - "+ desc);
}
});
}
$("a[href^='http']").each(function () {
var href= this.getAttribute("href");
$(this).prepend('<img src="https://www.google.com/s2/favicons?domain='+ href +'">';
grabber( href , this ); // this represent the current loop el.
});
<script>