Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

Changing the Value of an Attribute

To modify the value of an HTML attribute, use the following syntax:

document.getElementById(id).attribute = new value

This example updates the value of the src attribute of an <img> element:

Example

<!DOCTYPE html>
<html>
<body>

<img id=”myImage” src=”smiley.gif”>

<script>
document.getElementById(“myImage”).src = “landscape.jpg”;
</script>

</body>
</html>

In the example, an HTML <img> element with id="myImage" is accessed via the DOM, and JavaScript changes its src attribute from "smiley.gif" to "landscape.jpg".