user143805
user143805

Reputation: 31

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.

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.

Upvotes: 2

Views: 9818

Answers (5)

coderjoe
coderjoe

Reputation: 11177

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

Upvotes: 1

Christian C. Salvad&#243;
Christian C. Salvad&#243;

Reputation: 827932

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

Upvotes: 1

Jonathan Fingland
Jonathan Fingland

Reputation: 57187

use:

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

Upvotes: 1

Joel
Joel

Reputation: 19368

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

Upvotes: 0

chaos
chaos

Reputation: 124355

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

Upvotes: 1

Related Questions