Changing element attributes

Microsoft introduced a way to change HTML element attributes and their values. This was outerHTML and should never be used as it will not work on most browsers. Instead you can change the values using the JavaScript DOM:

document.getElementById('picture').src='freda.jpg';
        

That changes the value of the src attribute (meaning that the image will change). Here is a working example:

            
function changepic(){
    
    if (document.getElementById('firstpic').alt=='picture of fred') {
        var newsrc='freda.jpg';
        var newalt='picture of freda';
    } else {
        var newsrc='fred.jpg';
        var newalt='picture of fred';
    }
                    
    document.getElementById('firstpic').src=newsrc;
    document.getElementById('firstpic').alt=newalt;
    
}
            
        

This function looks at what the current picture is and changes it to the other one. The ALT attribute is changed as well and if there were more attributes (CLASS maybe) they would have to be changed as well. Outerhtml would allow you to re-write the whole HTML element in one go (in IE) but the DOM model forces you to do it in two or more parts.

This is the HTML which is needed to trigger the function:

<img id="picture" src="fred.jpg" alt="picture 1" onclick="changepic()">        
        

Copy those into a new Web page called picswap.html. You will also need two images which are called fred.jpg and freda.jpg and are saved in the same place as your new Web page (although it will work without the images). Try the page by clicking on the image.

submit to reddit Delicious Tweet