Reputation: 8070
I am not sure is possible or not but someone know suggest me if possible.
For example:
<a href="image/image.jpg"><img src="image/image.jpg" alt="image"/></a>
in this how to change the href path to another image dynamically using jquery. i.e.,
<a href="image/img.jpg"><img src="image/image.jpg" alt="image"/></a> like this.
EDITED: If
<a href="#"><img src="image/image.jpg"/></a>
<a href="http://stackoverflow.com"><img src="image/image.jpg"/></a>
<a href="image/image.jpg"><img src="image/image.jpg"/></a>
How can i vary this href attr
that condition should satisfy only when the anchor tag of href link contain image. then the anchor text is should img
tag.
Here is the JSFIDDLE: http://jsfiddle.net/HMsSE/9/ Any suggestion would be much appreciated.
Thanks, vicky
Upvotes: 0
Views: 12878
Reputation: 17228
as topicstarter aksed, change performs on image click
$('img').click(function() {
$(this).parent('a').attr("href","image/img.jpg");
});
if you want to check href too, you have to use a condition
$('a').click(function() {
event.preventDefault();
if ($(this).attr('href').search('jpg')!=-1)
$(this).attr("href","image/img.jpg");
});
also, I have to mention that <img>
inside <a>
is not always responsive for click
oh yeah, fiddle UPD I don't know how could I forget about filter
$('a').click(function() {
event.preventDefault();
$(this).filter('[href*=jpg],[href*=png],[href*=gif]').attr("href","image/img.jpg");
});
Upvotes: 2
Reputation: 782
You can also do this in native Javascript without including jQuery
element.setAttribute(attributename,attributevalue)
Hope this will help you.
Upvotes: 0
Reputation: 56509
Also you can try using .prop()
$('a').prop('href', 'image/img.jpg')
From your comments, you're trying to change the href
of a
tag when it has a child element img
. If so,
if($('a').find('img').length) { // it return the no. of img tag within a
$('a').prop('href', 'image/img.jpg');
}
Upvotes: 2
Reputation: 14025
Just use attr
function
$('a').attr('href','image/img.jpg');
You can change it also by id which would be more useful
<a id="myLink" href="image/image.jpg"><img src="image/image.jpg" alt="image"/></a>
$('#myLink').attr('href','image/img.jpg');
Upvotes: 2
Reputation: 1039080
You could try using the .attr()
function to set the href to the new value:
$('a[href="image/image.jpg"]').attr('href', 'image/img.jpg');
Of course it probably would be easier if you give the anchor an unique id:
<a href="image/image.jpg" id="myLink"><img src="image/image.jpg" alt="image"/></a>
So that you could more easily select it:
$('#myLink').attr('href', 'image/img.jpg');
Upvotes: 3