0

I have following hyperlink in asp.net:

<asp:HyperLink ID="a" runat="server" ImageUrl="1.png" NavigateUrl="https://google.com/"></asp:HyperLink>

I want to change ImageUrl through jquery to 2.png. I am trying this but it is not working:

$("#a").attr("ImageUrl", "2.png");
4
  • Check the html that <asp:HyperLink> creates. Html uses the src attribute and not "ImageUrl". Commented Feb 1, 2012 at 19:50
  • @SérgioMichels - i tried using this also: $("#a").attr("src", "2.png"); and that does not work either. Commented Feb 1, 2012 at 19:52
  • did you checked the html that asp generated? Commented Feb 1, 2012 at 19:53
  • Is the image 2.png in the same folder as the web page? Otherwise you need to specify a folder location in the "src" property. Commented Feb 1, 2012 at 19:56

3 Answers 3

3

imageurl doesn't exist when it renders client side. It should transform your asp control to something like this.

<a href="/myurl.aspx"><img src="/my/image.jpg" /></a>

you should use something like

$("#<%=a.ClientID%>").find("img").attr("src", "2.png");

I didn't test this, but it should get you on the right path.

Sign up to request clarification or add additional context in comments.

Comments

2

A couple things here...

I have found that you can't select an element this way if you include the runat attribute. You will need to reference the object like this...

var hyperLink = document.getElementById("<%= a.ClientID %>");

That should get you the correct object. Now, the asp:HyperLink saves as an anchor with an image attached. So you can reference and change the source like this.

$(hyperLink).find("img").attr('src', '2.png');

Comments

1

You need to look at the markup as rendered by .NET rather than the server side code.

So, by looking at the markup, you'll see that this:

<asp:HyperLink ID="a" runat="server" ImageUrl="1.png" NavigateUrl="https://google.com/"></asp:HyperLink>

renders this (At least in .net 4.0):

<a id="a" href="https://google.com/">
    <img alt="" src="1.png">
</a>

While in my little test project the markup id matches the webforms id, this isn't always the case.

So, to change the image with jquery, you'd just say:

$('img', $('#<%= a.ClientID %>')).attr('src', '2.png');

This finds the image tag inside the tag with the ID of a and changes it's src attribute.

A word of advice - use better ID names than 'a'. You're markup needs to be easily decipherable. Also, when dealing with webforms (like I said above), always use <%= tagid.ClientID %> in the jquery.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.