Javascript Change HTML Element Attributes Tutorial

In this Javascipt tutorial we learn how to manipulate HTML element attributes.

We discuss how to check if an element exists, how to return its value or change it.

How to get a single HTML element's attribute

We can return a single attribute from an HTML element with the getAttribute() method.

This method takes the attribute’s name that we want to return as an argument.

Syntax:
 element.getAttribute("attribute_name");
Example:
<html>
<body>
  <a href="https://www.koderhq.com">Link</a>

  <p></p>
</body>
<script>
  const p = document.querySelector("p");

  // get the href attribute from
  // the anchor tag (link) element
  const a = document.querySelector("a").getAttribute("href");

  // show it in a paragraph
  p.innerHTML = a;
</script>
</html>

In the example above, we get the href attribute from the a tag directly on the selector method.

How to change a single HTML element's attribute

We can change the value of a single attribute with the setAttribute() method.

This method takes the name of the attribute whose value we want to set as the first argument, and the value we want to set it to as the second argument.

Syntax:
 element.setAttribute("attribute_name", "new_value");
Example:
<html>
<body>
  <a href="https://www.koderhq.com">Link</a>
</body>
<script>
  // set the href attribute
  // to a different link
  document.querySelector("a").setAttribute("href", "https://www.google.com");
</script>
</html>

In the example above, we change the url of the link to point to another website by setting a different value for the href attribute.

How to check if an HTML element attribute exists

If we’re not sure if an element has an attribute, we can do a simple conditional check with the hasAttribute() method.

The method takes the attribute name as an argument and returns true if the attribute exists.

Syntax:
 element.hasAttribute("attribute_name");
Example:
<html>
<body>
  <a href="https://www.koderhq.com">Link</a>
</body>
<script>
  const x = document.querySelector("a");

  // check if the 'a' tag has
  // the 'href' attribute
  if(x.hasAttribute("href")) {

    x.setAttribute("href", "https://www.google.com");
    x.innerText = "Google";
  }
</script>
</html>

In the example above, we check if the a tag has the href attribute.

Summary: Points to remember

  • Javascript allows us to get attributes, or set their values, in a selected HTML element.
    • To return an attribute’s value, we use the getAttribute method with the attribute name we’re looking for as argument.
    • To set an attributes’s value, we use the setAttribute method with the attribute name and a new value as argument.
  • To see if an element contains a specific attribute, we use the hasAttribute() method.