If the <img>
is inside the anchor, you could do it like this;
$("a[href*='http://'], a[href*='https://']").not("[href*='"+location.hostname+"']").each(function() {
var $this = $(this).addClass("external").attr("target","_blank");
var img = $this.children('img[alt]');
$this.attr("title", img.length ? img[0].alt : "Open link in new window");
});
There are a few changes here, your current selector looks at only <a>
in the first http://
check, but then looks at all elements in your https://
check, so this will be much more efficient. Then we're checking if the current element has a <img>
inside, if it does and it has an alt
attribute we use that, otherwise we give it the default title.
Or, another method, use what you have (change the selector to be efficient though) and afterwards set the titles for anchors that contain images, like this:
$("a.external > img[alt]").each(function() {
$(this).parent().attr("title", this.alt);
});