views:

81

answers:

2

Change all links that have an image in it to: javascript(alert(thehref));

eg.

<a href="/galleries/anna-leah-111827/image01.html"><img src="/source_galleries/anna-leah-111827/tn/01.jpg"></a>
<a href="/galleries/23435/image01.html">ssss</a>

becomes

<a href="/galleries/anna-leah-111827/image01.html" onclick="alert(this.href)"><img src="/source_galleries/anna-leah-111827/tn/01.jpg"></a>
<a href="/galleries/23435/image01.html">ssss</a>

How can I do that as a bookmarklet which uses an external JavaScript file.

I've been trying all day to no avail.

+4  A: 
for (var i= document.links.length; i-->0;) {
    if (document.links[i].getElementsByTagName('img').length!=0) {
        document.links[i].onclick= function() {
            alert(this.href);
        };
    }
}

encoded into a bookmarklet:

javascript:for%28i%3Ddocument.links.length%3Bi--%3E0%3B%29if%28document.links%5Bi%5D.getElementsByTagName%28%27img%27%29.length%21%3D0%29document.links%5Bi%5D.onclick%3Dfunction%28%29%7Balert%28this.href%29%3B%7D%3Bvoid%280%29%3B
bobince
if you don't want to follow the link, add `return false` to the event handler; you might also want to move the function literal out of the loop for performance reasons (there's no need to create a new function object for each link: the event handler can easily be shared)
Christoph
+1  A: 

I would include jQuery in the external file, use noconflict mode, and do something like this:

$('a:has(img)').bind('click', function(event){
    event.preventDefault();
    alert($(this).children('img').get(0).attr('src'));
}
cpharmston