sun
sun

Reputation: 1668

How to get href value of anchor tag if it has image tag in it

i tried to get the image src with jquery here is the code below

jQuery("img").click(function() {
    var im = $(this).attr('src'); 
    alert(im);
    return false;
});

above working fine i can get the image src. likewise i try to get href value of anchor tag only if it has a image tag in it otherwise it shouldn't.Below is a example containing image tag in it.

<a href="some.something"><img src="image1.jpg"></a>

how to do this?what selector is better?any idea?

Upvotes: 2

Views: 2066

Answers (2)

raam86
raam86

Reputation: 6871

$('img').parent('a') // Will select anchors who are `img` elements parents. 

$('img').parent('a').each(function(_,el){console.log(el.href)}); // will take the href attr.

To use with click function:

$('img').click(function(e){
e.preventDefault();//I use this to not direct myself to linked page for testing
var parent = $(e.target).parent('a');
console.log(parent.attr('href'));
})

Upvotes: 4

Rikard
Rikard

Reputation: 7805

Demo here

It's always easier if you have an id on the image.

  • To check if image src has parent that is a <a> you can use: if ($(this).parent('a').length) {

Inside the function triggered by click on image:

  • To get href value from parent that is a <a> tag you can use: $(this).parent('a').prop('href');
  • To get src value from the image use $(this).prop('src');

The whole code:

$('img').click(function () {
    $(this).preventDefault;
if ($(this).parent('a').length) {
    var im = $(this).prop('src');
    var aHref = $(this).parent('a').prop('href');
    alert('First alert with imc src: '+im);
    alert('Second alert with link href: '+aHref);
}
});

Upvotes: 2

Related Questions