I want to replace the gif file by javascript. I find the method below. Is there any way i can place the javascript tag before the img tag?
<img class="myImg" src="compman.gif" width="107" height="98">
<script>
document.getElementsByClassName("myImg")[0].src = "hackanm.gif";
</script>
I believe OP's main concern was flash of the old image before it is replaced by JavaScript. I suggest you add a line of CSS to make your image element visibly hidden then do the swap + unhide with JavaScript.
A page can't be manipulated safely until the document is "ready." Using jquery's
$(document).ready()
, it Will wait until the page is loaded and ready to be manipulated before executing (no matter where it is on the page). Example:You could also then leverage selectors inside jquery (e.g.
$(".class")
where class is your class, or$("#id")
where id is the id) and change the code to:And further you could even store it in a variable if you wanted to change it later on in javascript as well!
Hope this helps you learn a few new tricks inside javascript! Happy coding!
More Info