[thelist] How to apply same function to all the images

Alex Beston alex.beston at gmail.com
Wed Oct 13 13:27:18 CDT 2010


Amrit

try this:

<html>
<head>
<script type="text/javascript"
src="http://code.jquery.com/jquery-latest.js"></script>
 <script type="text/javascript">

function setAllImageWidths(newwidth){
	$('.myimage').attr("width", newwidth);
}
	
function undoSetWidths(){
	$('.myimage').removeAttr("width");
}


</script>	
</head>
<body>
<img src='http://www.cardsunlimited.com/largeimage/ChristmasRobin.jpg'
class="myimage"  />

<img src='http://louisey.files.wordpress.com/2009/10/red-tractor.jpg'
class="myimage" />
<p>
<button onclick="setAllImageWidths(100);">Image widths 100</button>

<button onclick="setAllImageWidths(1000);">Image widths 1000</button>	

<button onclick="undoSetWidths();">Original width</button>	


</p>
</body>

</html>	

...

So what you do is set the images to a generic label e.g.
class="myclass", change the attributes of myclass and youre good to
go.


you see the problem is JS doesnt come with a getelementbyclass for the
obvious reason that it would have to get a multiplicity of elements
whereas an id is just one element, so it makes sense to have a
getElementById.

However someone has written a getElementByClass which is here:

http://forums.devshed.com/javascript-development-115/javascript-get-all-elements-of-class-abc-24349.html

and ofcourse, jquery has it aswell, which you'd be alot safer using.
have a read of:

http://docs.jquery.com/How_jQuery_Works

Happy coding,

Alex


More information about the thelist mailing list