Javascript Get, Set and Remove Attribute Example

In this tutorial you will learn how to get, set and remove the value of a specified attribute on an html element.

First example will show how to get an attribute from an html div element in javascript easily. Next example will show you to set an attribute in a specified element and the third example will work for how to remove an attribute from html element.

JavaScript getAttribute() example

The getAttribute() method is used to get the current value of a attribute on the element. If the attribute exists on the element, the getAttribute() returns a string that represents the value of the attribute. If the specified attribute does not exist on the element, it will return null. So you can use the hasAttribute() method to check if the attribute exists on the element before getting its value. Here’s an example:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>JS getAttribute() Demo</title>
</head>
<body>

<a href="https://www.codingdriver.com/" target="_blank" id="get-attribute">Coding Driver</a>

<script>
    // Selecting the element by ID attribute
    var link = document.getElementById("get-attribute");

    // Getting the attributes values
    var href = link.getAttribute("href");
    alert(href); // Outputs: https://www.codingdriver.com/

    var target = link.getAttribute("target");
    alert(target); // Outputs: _blank
</script>
</body>
</html>

Javascript Set Attributes Example

The setAttribute() method is used to set an attribute on the specified element. If the attribute and its have value is already exists on the element, the value is updated; otherwise a new attribute is added with the specified name and value. The following example will update the value of the existing href attribute of an anchor () element.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>JS setAttribute() Demo</title>
</head>
<body>


<a href="#" id="get-attribute">Coding Driver</a>

<script>
    // Selecting the element
    var link = document.getElementById("get-attribute");
	
    // Changing the href attribute value
    link.setAttribute("href", "https://www.codingdriver.com");
</script>
</body>
</html>

Javascript Remove Attributes Example

The removeAttribute() method is used to remove an attribute from the specified element. Here the following example will remove the href attribute from an anchor element.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>JS removeAttribute() Demo</title>
</head>
<body>


<a href="#" id="get-attribute">Coding Driver</a>

<script>
    // Selecting the element
    let link = document.getElementById("get-attribute");
	
    // Removing the href attribute
    link.removeAttribute("href");
</script>
</script>
</body>
</html>

Related Searches: Javascript get attributre, Javascript set Attribute, Javascript remove attribute

Leave a Comment