up vote 2 down vote favorite

Hi I am currently trying to replace a query string value in a a link's src attribute.

it works fine in firefox but not in ie.

example:

<a id="link" href="#" src="http://somedomain.com?id=123&size=20">link</a>

then on my js it looks kinda like this:

var link = document.getElementById('link');
link.src.replace('size=20', 'size=45');

in ie, it returns something like src is not an object error;

anyone kind enough to lend a hand?

also, i need this to be on native javascript so please don't suggest a framework as a solution thanks.

flag

0% accept rate
You might also want is use the Regex with replace, w3schools.com/jsref/jsref_replace.asp – BigBlondeViking Jul 23 '09 at 15:19

5 Answers

up vote 1 down vote

To get it to work in IE you're going to need to use link.setAttribute('src', ...).

link|flag
up vote 1 down vote

Well, links (anchor elements) don't have a src attribute, I think that you want to change the href attribute:

var link = document.getElementById('link');
link.href = link.href.replace('size=20', 'size=45');
link|flag
Good point. Though he could be using src as a custom attribute, in which case setAttribute and getAttribute come back into play. – Joel Potter Jul 23 '09 at 15:23
well yeah sorry bout that, i used a wrong example (im really fussed lol)... in my real case, its an img tag... im trying to display gravatar images... on preview i use smaller thumbnails hence the s=18 query string. but on click, i want to replace the s=18 with s=45 and place the result on a textbox. – user143805 Jul 23 '09 at 15:31
up vote 0 down vote

I believe getAttribute is more cross-browser friendly.

var link = document.getElementById('link');
var result = link.getAttribute("src").replace('size=20', 'size=45');

Also, the replace function returns a string. It doesn't operate on the string it is called against. This means you have to assign the result.

link.setAttribute("src", result);
link|flag
up vote 0 down vote

use:

var link = document.getElementById('link');
var src = link.getAttribute("src").replace('size=20', 'size=45');
link.setAttribute("src", src);
link|flag
up vote 0 down vote

In your case the "src" attribute in your link is an expando attribute, since an anchor tag does not have a src.

When working with expando attributes, it's safest to set and get the values using the setAttribute('attributeName',value) and getAttribute('attributeName') accessors.

To find out more about getAttribute and setAttribute you can check here:

To find out more about DHTML properties you can check the MSDN Resource here:

Example Code using getAttribute and setAttribute:

var link = document.getElementById('link');
var src = link.getAttribute('src');
link.setAttribute('src',src.replace('size=20','size=40'));
link|flag

Your Answer

get an OpenID
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.