CSE 154 Examples

Using Javascript to Change Attributes of DOM Elements

Description :

Javascript can be used to change Attributes of DOM Elements. Attributes are components of a DOM element that give it more meaning. For example, if we have an img tag :

<img src="tree.jpg" alt="A tree!" /> , the src and alt text components are attributes of the img DOM element.

Javascript gives us the capability to access these DOM elements. Once we have access, we can change the attributes as needed.

Example :

Image showing a dog(sad)

In this case JavaScript, accesses the img DOM element when the button is clicked and changes the value of the src (source) attribute of an image.
NOTE that in this case, we're not changing the img element. The img element remains the same and we're only changing the src attribute. Code for this can be found below:

					
						document.getElementById("dog").src = "changed_img.jpeg";