Changing Image Src attribute using Title attribute... Possible..?? How??? With Javascript....


Is it possible to use JS to alter the "src" attribute of an image tag using the "Title" attrubute to get the relevant tag.

So my full image tag is:

<img title="My Test Image" src="../Images/test.jpg" />

could be converted to:

<img title="My Test Image" src="../Images/test1000.jpg" />

using something like

Image = GetElementByTitle('My Test Image');
Image.Src = '../Images/test1000.jpg';

This image tag is autogenerated by something else hence the reason for not having the "ID" to play with.

Thanks in advance...

Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

RobinSoftware EngineerCommented:
Couldn't you enumerate all img tags in the document and pick the one you want to change?

function testImg()
   for (var i = 0; i < lst.length; i++) {
      if(lst[i].title=='My Test Image') lst[i].src='../Images/test1000.jpg';

Open in new window

You don't even need document.getElementsByTagName(). The browser already has an images array/collection built in that references the images on the page:

for( var i=0;i<document.images.length; ++i)
  if( document.images[i].title=='My Test Image')

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
perhaps clubbing both....

	<title>Images Test</title>
	<script type='text/javascript'>
	  // function that return an array of images with the title in question
	  document.getImagesByTitle = function(title) 
			var retnode = [];
			var imageTitle = new RegExp( '\\b' + title + '\\b' );
			var images = document.images;
			for( var i=0; i<images.length; ++i)
			  if( imageTitle.test(title))
					retnode.push( images[i]);
			return retnode;
	 window.onload = function(){
		var imgArray = document.getImagesByTitle("EE");
		imgArray[0].src = "";
		<img src="" title="EE"></img>

Open in new window

SamJollyAuthor Commented:
thx all
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.