How to Set HTML Attributes Using JavaScript?

Estimated read time 2 min read

You can set HTML attributes using JavaScript by accessing the element and modifying its properties. Here’s an example that sets the src attribute of an img element with an id of “myImage”:

<img id="myImage" src="old-image.jpg">

<button onclick="setImage()">Set Image</button>

<script>
  function setImage() {
    const image = document.getElementById("myImage");
    image.src = "new-image.jpg";
  }
</script>

In the example above, the setImage() function uses JavaScript to access the img element with an id of “myImage”. The function then sets the src attribute of the img element to “new-image.jpg”. When the “Set Image” button is clicked, the function is triggered and changes the src attribute of the img element, causing it to display a different image.

You can set any attribute of an HTML element in a similar manner by accessing the element and modifying its properties. For example, to set the alt attribute of an img element, you would modify its alt property:

<img id="myImage" src="image.jpg" alt="Old Alt Text">

<button onclick="setAltText()">Set Alt Text</button>

<script>
  function setAltText() {
    const image = document.getElementById("myImage");
    image.alt = "New Alt Text";
  }
</script>

In the example above, the setAltText() function uses JavaScript to access the img element with an id of “myImage”. The function then sets the alt attribute of the img element to “New Alt Text”. When the “Set Alt Text” button is clicked, the function is triggered and changes the alt attribute of the img element.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply