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



Question:

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.


Solution:1

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


Solution:2

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


Solution:3

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


Solution:4

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


Solution:5

use:

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
Previous
Next Post »