What You Need To Know About JavaScript DOM Get Set

Posted by TotalDC

In this tutorial lets look at JavaScript DOM Get Set and how to get, set and remove attributes from HTML elements in JavaScript. And if you missed last article you can find it here.

Working With Attributes In JavaScript

The attributes are special words used inside the start tag of an HTML element to basically control tag’s behaviour 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 then 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>

    // 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

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 – new attribute is added with the specified name and value. The JavaScript code in the following example will add a class and disabled attribute tu the <button> element. Here’s how it looks:

<button type="button" id="myBtn">Click Me</button>

    // Selecting the element
    let btn = document.getElementById("myBtn");
    // Setting new attributes
    btn.setAttribute("class", "click-btn");
    btn.setAttribute("disabled", "");

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>

    // Selecting the element
    let link = document.getElementById("myLink");
    // Changing the href attribute value
    link.setAttribute("href", "https://www.simplywebstuff.com");

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>

    // Selecting the element
    let link = document.getElementById("myLink");
    // Removing the href attribute

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.