What You Need To Know About JavaScript DOM Get Set
Posted by TotalDCIn this tutorial let’s look at JavaScript DOM Get Set and how to get, set, and remove attributes from HTML elements in JavaScript.
Working With Attributes In JavaScript
The attributes are special words used inside the start tag of an HTML element to control the tag’s behavior or provide additional information about the tag.
JavaScript gives you several methods for adding, removing, or changing HTML element’s attributes.
How To Get Element’s Attribute Value In JavaScript
For this, you can use getAttribute() method. This method is used to get the current value of an attribute on the element. In case the specified attribute does not exist on the element, it will return null. Here’s an Example:
<a href="https://www.simplywebstuff.com/" target="_blank" id="myLink">Simply Web Stuff</a>
<script>
// Selecting the element by ID attribute
let link = document.getElementById("myLink");
// Getting the attributes values
let href = link.getAttribute("href");
console.log(href); // Result: https://www.simplywebstuff.com/
let target = link.getAttribute("target");
console.log(target); // result: _blank
</script>
How To Set Attributes On An Element In JavaScript
The setAttribute() method is used to set an attribute on the specified element.
If the attribute already exists on the element, the value is updated. If not – a new attribute is added with the specified name and value. The JavaScript code in the following example will add a class and disabled attribute to the <button> element. Here’s how it looks:
<button type="button" id="myBtn">Click Me</button>
<script>
// Selecting the element
let btn = document.getElementById("myBtn");
// Setting new attributes
btn.setAttribute("class", "click-btn");
btn.setAttribute("disabled", "");
</script>
You can use the setAttribute() method to update or change the value of an element, because as I mentioned if an element already exists, JavaScript will not create a duplicate, but simply overwrite the value of an existing HTML element. Let’s look at how it works:
<a href="#" id="myLink">Simply Web Stuff</a>
<script>
// Selecting the element
let link = document.getElementById("myLink");
// Changing the href attribute value
link.setAttribute("href", "https://www.simplywebstuff.com");
</script>
How To Remove Attributes From Elements Using JavaScript
For this job, you will need the removeAttribute() method. And here’s how it looks:
<a href="https://www.simplywebstuff.com/" id="myLink">Simply Web Stuff</a>
<script>
// Selecting the element
let link = document.getElementById("myLink");
// Removing the href attribute
link.removeAttribute("href");
</script>