How to change the attributes (e.g., src, href) of HTML elements using JavaScript?

To change the attributes of HTML elements using JavaScript, you can use the setAttribute() and getAttribute() methods. Here's an example of how to change the src attribute of an image element and the href attribute of a link element:

  1. Get the reference to the element you want to modify using the getElementById(), getElementsByClassName(), getElementsByTagName(), or other DOM manipulation methods. For example:
var image = document.getElementById("imageId"); var link = document.getElementsByClassName("linkClass")[0];
  1. Change the attribute values using the setAttribute() method. For example:
image.setAttribute("src", "newImage.jpg"); link.setAttribute("href", "https://example.com");
  1. You can also retrieve the current attribute values using the getAttribute() method. For example:
var currentSrc = image.getAttribute("src"); console.log("Current src: " + currentSrc); var currentHref = link.getAttribute("href"); console.log("Current href: " + currentHref);
  1. To remove an attribute, you can use the removeAttribute() method. For example:
link.removeAttribute("href");

Note: Make sure to replace "imageId" with the actual id of the image element and "linkClass" with the actual class name of the link element you want to modify.