Tutorial :Javascript: replace a string in element.src attribute


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.


<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.


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


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');  


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'));  


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);  



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

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »