Monday, May 6, 2024
HomeCSSEasy methods to Use DOM to Change Attributes and Courses of Parts

Easy methods to Use DOM to Change Attributes and Courses of Parts


A webpage consists of a wide range of HTML components that are created utilizing completely different tags. Some frequent tags embrace the <html> tag which represents the basis of an HTML doc, the <physique> tag which represents the content material of the doc, the p tag which represents paragraphs and so forth.

Totally different tags that you just use to create a webpage also can have completely different attributes connected to them. These attributes will both change the looks or conduct of the weather or present extra metadata. Some examples of attributes embrace id, class, contenteditable, minlength, maxlength, and sample.

On this tutorial, we are going to discover ways to manipulate completely different attributes of any ingredient on a webpage.

Getting Attribute Values from Parts

We are able to name the getAttribute() methodology on our ingredient and cross it the identify of our attribute to retrieve its worth. The return worth of this methodology is a string that represents the worth of the attribute.

You’re going to get again null when the attribute whose worth you’re retrieving doesn’t truly exist.

Let’s attempt to get the attribute values for the ordered record within the following markup:

1
<h1>Most Populated International locations</h1>
2

3
<ol sort="I" begin="10" reversed="true">
4
  <li>Mexico</li>
5
  <li>Russia</li>
6
  <li>Bangladesh</li>
7
  <li>Nigeria</li>
8
  <li>Brazil</li>
9
</ol>

Right here is the JavaScript that will get the worth of all three attributes:

1
let pop_countries = doc.querySelector("ol");
2

3
// Output: 10
4
console.log(pop_countries.getAttribute("begin"));
5

6
// Output: true
7
console.log(pop_countries.getAttribute("reversed"));
8

9
// Output: I
10
console.log(pop_countries.getAttribute("sort"));

Setting Attribute Values for Parts

As I discussed earlier, attributes are used to both change the conduct of a component or present extra metadata. You may have to replace the worth of an current attribute to one thing else or add a brand new attribute to a component.

You should utilize the setAttribute() methodology in both case. It accepts two parameters—the attribute identify and the attribute worth. The attribute identify needs to be a string and it is going to be transformed to all lowercase. The attribute worth can also be a string and any non-string values shall be routinely transformed to a string.

Contemplate the next markup:

1
<ol sort="I" begin="10" reversed="true">
2
  <li>Brazil</li>
3
  <li>Nigeria</li>
4
  <li>Bangladesh</li>
5
  <li>Russia</li>
6
  <li>Mexico</li>
7
</ol>

The next JavaScript will replace the worth of sort, begin and reversed attributes in our record:

1
let pop_countries = doc.querySelector("ol");
2

3
pop_countries.setAttribute("sort", "i");
4
pop_countries.setAttribute("begin", "6");
5
pop_countries.setAttribute("reversed", "false");

This leads to the next markup:

1
<ol sort="i" begin="6" reversed="false">
2
  <li>Brazil</li>
3
  <li>Nigeria</li>
4
  <li>Bangladesh</li>
5
  <li>Russia</li>
6
  <li>Mexico</li>
7
</ol>

The next picture exhibits the way to order record was rendered initially and after the updates to attribute values.

Ordered List AttributesOrdered List AttributesOrdered List Attributes

As you may see, the counting order continues to be reversed regardless that we’ve got set the worth of reversed to false. The explanation this occurs is as a result of reversed is a Boolean attribute and setting it to any worth will lead to its worth being thought of true.

It is suggested that you just set the worth of such attributes to both an empty string or attribute names if you’d like them to be true. The one solution to forestall the reversal from taking place is to take away the attribute totally utilizing the removeAttribute() methodology.

1
pop_countries.removeAttribute("reversed");

Add, Take away, Change or Toggle Component Courses

You most likely already know concerning the class attribute that we will use with completely different HTML components to supply a space-separated record of lessons. Courses play an essential function in collection of components for both making use of some styling or scripting.

Including, eradicating, changing and toggling lessons of a component is definitely a quite common job in internet improvement. A component may should be in lively or inactive state which you’ll be able to present by use of various lessons.

Though we will use the getAttribute() and setAttribute() strategies to do all these operations on a component’s lessons, it’s far more handy to simply use the read-only classList property together with its add(), take away(), change() and toggle() helper strategies.

The add() Methodology

The classList property provides again a DOMTokenList of lessons connected to the queried ingredient. You should utilize the add() methodology so as to add new tokens or class names to the record. It’s potential to cross a number of class names to this methodology and any current token is not going to be added twice however merely omitted.

Listed below are some examples of utilizing this methodology:

1
let message = doc.querySelector(".message");
2

3
// Add a single class
4
message.classList.add("notification");
5

6
// Add a number of lessons
7
message.classList.add("alert", "message");

The take away() Methodology

You should utilize the take away() methodology if you wish to take away a number of lessons from a component. No errors shall be thrown if the category that you just need to take away from a component is already absent from the ingredient’s class record.

Listed below are some examples of utilizing this methodology:

1
let message = doc.querySelector(".message");
2

3
// Take away a single class
4
message.classList.take away("notification");
5

6
// Take away a number of lessons
7
message.classList.take away("alert", "hidden");

The toggle() Methodology

The toggle() methodology is beneficial if you need to take away a category whether it is within the DOMTokenList and add a category if it isn’t within the DOMTokenList. This methodology can settle for both one or two parameters. The primary parameter is the identify of the category that you just need to toggle. The second parameter is a situation that you just need to test earlier than you toggle the category. When the second parameter returns false, the category can solely be eliminated and never added. When the second parameter returns true, the category can solely be added and never eliminated.

This methodology returns true when a category is added to the DOMTokenList and returns false when a category is faraway from the DOMTokenList. You should utilize the return worth to substantiate if the category is current or absent after the operation.

1
message.classList.toggle("hidden");

The change() Methodology

Some instances, we need to change an current class with a brand new one and do nothing if the outdated class is not already connected to the ingredient. The change() methodology works greatest on this case. It’ll return false if the substitute failed and true if the substitute was profitable.

Right here is a few code that listens to the press occasion on a button after which takes all paragraphs with a specific class and replaces that class with a brand new one.

1
done_btn.addEventListener("click on", (evt) => {
2
  let planned_tasks = doc.querySelectorAll(".will-do");
3
  
4
  for(job of planned_tasks) {
5
    job.classList.change("will-do", "finished");
6
  }
7
});

The next CodePen exhibits all these 4 strategies in motion with the lessons add, eliminated, toggled or changed primarily based on button clicks.

Closing Ideas

On this tutorial, we’ve got realized about native JavaScript strategies so as to add, replace or take away attributes to completely different components in your webpage. It is rather frequent for builders to control the lessons related to a component. JavaScript means that you can do it far more simply with the classList property and its helper strategies.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments