Managing HTML Element Attributes with ClassList and Attribute Methods in JavaScript


In JavaScript, the classList and attribute methods are used for manipulating the class and attribute values of an HTML element.

The classList method provides a set of built-in functions that allow developers to add, remove, or toggle class names of an element. These functions include add(), remove(), toggle(), and contains(). Using these functions, you can easily change the appearance and behavior of an element based on user interaction or other events.

On the other hand, the attribute method provides a way to get, set, or remove the attribute value of an element. This method accepts one or two parameters: the first parameter is the name of the attribute, and the second parameter (optional) is the new value of the attribute.

classList

The classList property returns a DOMTokenList object, which represents the class attribute of an element as a collection of space-separated tokens. You can use the methods of this object to manipulate the classes of the element.Here are some common methods of the classList object

Adding a class

The add() method belongs to the classList property, which is available on all HTML elements. You can use the add() method to add a new class name to the list of classes that an element already has.

Note that if the element already has a class name that you're trying to add, the add() method will ignore that class name and not add it again. This ensures that each class name in the list of classes is unique.

To add a new class to an element, you can use the add() method. For example:

<div class="box">Box</div>

JavaScript Code

const btnAdd = document.querySelector("#btnAdd");
btnAdd.addEventListener("click", function () {
  box.classList.add("new-color");
});
  1. This line of code selects the button with an id of "btnAdd" using the querySelector() method and stores it in a variable called btnAdd.
  2. Next adds an event listener to the btnAdd button using the addEventListener() method. The event that we're listening for is a "click" event, which fires when the button is clicked.
  3. The second argument to addEventListener() is a function that will be executed when the event is triggered. In this case, we're passing in an anonymous function that will add a new CSS class to a box with an unknown id.
  4. We're adding the CSS class "new-color" to the box using the classList.add() method. This will apply a new style to the box, changing its background color to whatever is defined in the "new-color" CSS class.
  5. Note that the box variable isn't defined in this code snippet, so it's unclear what element this code is targeting. However, assuming that there is an HTML element with a class attribute of "box" on the page, this code would add a new CSS class of "new-color" to that element when the "btnAdd" button is clicked.

Removing a class

classList.remove() is a method in JavaScript that allows you to remove one or more CSS classes from an HTML element.

The remove() method belongs to the classList property, which is available on all HTML elements. You can use the remove() method to remove a class name from the list of classes that an element already has.The remove() method belongs to the classList property, which is available on all HTML elements. You can use the remove() method to remove a class name from the list of classes that an element already has.

Note that if the element doesn't have a class name that you're trying to remove, the remove() method will ignore that class name and not throw an error.

To remove a class from an element, you can use the remove() method. For example:

<button id="btnRemove">Remove</button>

JavaScript Code

const btnRemove = document.querySelector("#btnRemove");
btnRemove.addEventListener("click", function () {
  box.classList.remove("new-color");
});
  1. This code adds an event listener to a button with an id of "btnRemove" and removes a CSS class from a box when the button is clicked.
  2. The code selects the button with an id of "btnRemove" using the querySelector() method and stores it in a variable called btnRemove.
  3. This code adds an event listener to the btnRemove button using the addEventListener() method. The event that we're listening for is a "click" event, which fires when the button is clicked.
  4. The second argument to addEventListener() is a function that will be executed when the event is triggered. In this case, we're passing in an anonymous function that will remove a CSS class from a box with an unknown id.
  5. We're removing the CSS class "new-color" from the box using the classList.remove() method. This will remove the style that was previously applied to the box by the "new-color" CSS class, changing its background color back to whatever it was before the "new-color" class was added.
  6. Note that the box variable isn't defined in this code snippet, so it's unclear what element this code is targeting. However, assuming that there is an HTML element with a class attribute of "box" on the page, this code would remove the "new-color" CSS class from that element when the "btnRemove" button is clicked.

Toggling a class

The toggle() method belongs to the classList property, which is available on all HTML elements. You can use the toggle() method to add a class name to an element if it doesn't have it, or remove it if it already has it.

Note that the toggle() method returns a boolean value that indicates whether the class was added or removed. If the class was added, the method returns true. If the class was removed, the method returns false.

You can also use the toggle() method to conditionally add or remove a class based on a boolean value..

To toggle a class on an element (i.e., add it if it doesn't exist, remove it if it does), you can use the toggle() method. For example:

<button id="btnToggle">Toggle</button>

JavaScript Code

const btnToggle = document.querySelector("#btnToggle");
btnToggle.addEventListener("click", function () {
  box.classList.toggle("new-color");
});
  1. This line of code selects the button with an id of "btnToggle" using the querySelector() method and stores it in a variable called btnToggle.
  2. This code adds an event listener to the btnToggle button using the addEventListener() method. The event that we're listening for is a "click" event, which fires when the button is clicked.
  3. The second argument to addEventListener() is a function that will be executed when the event is triggered. In this case, we're passing in an anonymous function that will toggle a CSS class on and off a box with an unknown id.
  4. We're toggling the CSS class "new-color" on and off the box using the classList.toggle() method. This method will add the "new-color" class to the box if it doesn't have it, or remove it if it does have it.
  5. Assuming that there is an HTML element with a class attribute of "box" on the page, this code would toggle the "new-color" CSS class on and off that element when the "btnToggle" button is clicked.

Attribute

In JavaScript, the getAttribute() and setAttribute() methods are used to get and set attributes on an HTML element, respectively.

Getting an attribute value

To get the value of an attribute on an element, you can use the getAttribute() method.The getAttribute() method takes a single argument, which is the name of the attribute you want to get the value of. If the specified attribute doesn't exist on the element, the getAttribute() method will return null.Note that if the attribute you want to get is a standard HTML attribute, like href, src, or class, you can also access them directly as properties on the HTML element

However, if you want to get the value of a custom data attribute, you must use the getAttribute() method.

Setting an attribute value

To set the value of an attribute on an element, you can use the setAttribute() method.The setAttribute() method is used to set the value of a specified attribute on an HTML element.The setAttribute() method takes two arguments: the name of the attribute you want to set, and the value you want to set it to.

If the specified attribute doesn't already exist on the element, the setAttribute() method will create it. If the attribute already exists, the method will replace its value with the new value.Note that you can also set the value of standard HTML attributes, like href, class, or id, by directly setting their corresponding properties on the HTML element.

However, if you want to set the value of a custom data attribute, you must use the setAttribute() method.

For Example

<input type="text" id="txtName" class="apple" name="name" />
<button id="btnClick">Click</button>

JavaScript Code

const btnClick = document.querySelector("#btnClick");
const input = document.querySelector("input");

btnClick.addEventListener("click", function () {
  const getAtt = input.getAttribute("type");
  if (getAtt == "text") {
    input.setAttribute("type", "password");
  } else {
    input.setAttribute("type", "text");
  }
});

his JavaScript code adds a click event listener to a button with the ID "btnClick". When the button is clicked, the code retrieves the "type" attribute of an input element and checks if it equals "text". If it does, the code sets the "type" attribute of the input element to "password". If it doesn't, the code sets the "type" attribute to "text". This code allows a user to toggle between hiding and showing the value of a password input field.

  1. The const keyword is used to declare two variables: btnClick and input. btnClick is assigned the value of the HTML element with the ID "btnClick", which is a button element in this case. input is assigned the value of the first HTML input element on the page.
  2. The addEventListener() method is used to attach a click event listener to the btnClick element. The second argument of this method is a callback function that will be executed when the button is clicked.
  3. Inside the callback function, the getAttribute() method is used to get the current value of the type attribute of the input element, which is initially set to "text".
  4. The if statement checks if the value of getAtt is equal to "text". If it is, the setAttribute() method is used to change the value of the type attribute to "password". If it isn't, the setAttribute() method is used to change the value of the type attribute to "text".
  5. When the user clicks the button, the value of the type attribute of the input element is toggled between "text" and "password", allowing the user to toggle the visibility of the password in the input field.

Note that this method is not supported in Internet Explorer or some older browsers, so you may want to check for its availability before using it. One way to do this is to use the typeof operator to check if the method exists on the element

Removing an attribute value

The removeAttribute() method takes a single argument, which is the name of the attribute you want to remove.If the specified attribute doesn't exist on the element, the removeAttribute() method will do nothing.

Note that you can also remove standard HTML attributes, like href, class, or id, by setting their corresponding properties on the HTML element to null.

However, if you want to remove a custom data attribute, you must use the removeAttribute() method.

To remove an attribute from an element, you can use the removeAttribute() method. For example:

<input type="text" id="txtName" class="apple" name="name" />

JavaScript Code

const input = document.querySelector("input");
input.removeAttribute("name");

hasAttribute()

The hasAttribute() method takes a single argument, which is the name of the attribute you want to check.

If the specified attribute exists on the element, the hasAttribute() method will return true. If the attribute does not exist, the method will return false.

Note that you can also check for standard HTML attributes, like href, class, or id, by checking their corresponding properties on the HTML element.

However, if you want to check for a custom data attribute, you must use the hasAttribute() method.

For example:

<input type="text" id="txtName" class="apple" name="name" />

JavaScript Code

console.log(input.hasAttribute("class"));

getAttributeNames()

The getAttributeNames() method in JavaScript is used to retrieve an array of all attribute names of an HTML element.

Note that this method is not supported in Internet Explorer or some older browsers, so you may want to check for its availability before using it. One way to do this is to use the typeof operator to check if the method exists on the element:

Note that this method is not supported in Internet Explorer or some older browsers, so you may want to check for its availability before using it. One way to do this is to use the typeof operator to check if the method exists on the element:

For example:

<input type="text" id="txtName" class="apple" name="name" />

JavaScript Code

const input = document.querySelector("input");
let list = input.getAttributeNames();
console.log(list);

Example

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .box {
        width: 150px;
        height: 150px;
        background-color: palegreen;
        font-size: 20px;
        text-align: center;
        line-height: 150px;
        margin-bottom: 20px;
      }
      .new-color {
        color: orange;
        background-color: #222;
      }
    </style>
  </head>
  <body>
    <!--
    <div class="box">Box</div>
    <button id="btnAdd">Add</button>
    <button id="btnRemove">Remove</button>
    <button id="btnToggle">Toggle</button>
    -->
    <input type="text" id="txtName" class="apple" name="name" />
    <button id="btnClick">Click</button>
    <script src="script.js"></script>
  </body>
</html>

script.js

/*
classList.add();
classList.remove();
classList.toggle();
getAttribute();
setAttribute();

hasAttribute()
getAttributeNames()
removeAttribute()

*/
/*
const btnAdd = document.querySelector("#btnAdd");
const btnRemove = document.querySelector("#btnRemove");
const btnToggle = document.querySelector("#btnToggle");
const box = document.querySelector(".box");
btnAdd.addEventListener("click", function () {
  box.classList.add("new-color");
});
btnRemove.addEventListener("click", function () {
  box.classList.remove("new-color");
});

btnToggle.addEventListener("click", function () {
  box.classList.toggle("new-color");
});
*/

const btnClick = document.querySelector("#btnClick");
const input = document.querySelector("input");

btnClick.addEventListener("click", function () {
  const getAtt = input.getAttribute("type");
  if (getAtt == "text") {
    input.setAttribute("type", "password");
  } else {
    input.setAttribute("type", "text");
  }
});

console.log(input.hasAttribute("class"));
let list = input.getAttributeNames();
console.log(list);
input.removeAttribute("name");
list = input.getAttributeNames();
console.log(list);

List of Programs


JS Practical Questions & Answers


JS Practical Project