Thursday, November 30, 2023
HomeVideo EditingMethods to Use DOM to Change Attributes and Courses of Components

Methods to Use DOM to Change Attributes and Courses of Components


A webpage consists of quite a lot of HTML parts that are created utilizing completely different tags. Some frequent tags embody the <html> tag which represents the foundation 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 further metadata. Some examples of attributes embody id, class, contenteditable, minlength, maxlength, and sample.

On this tutorial, we are going to learn to manipulate completely different attributes of any factor on a webpage.

Getting Attribute Values from Components

We are able to name the getAttribute() methodology on our factor and move 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 checklist within the following markup:

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

3
<ol kind="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("kind"));

Setting Attribute Values for Components

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

You should use the setAttribute() methodology in both case. It accepts two parameters—the attribute identify and the attribute worth. The attribute identify must 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 might be routinely transformed to a string.

Take into account the next markup:

1
<ol kind="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 kind, begin and reversed attributes in our checklist:

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

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

This leads to the next markup:

1
<ol kind="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 right way to order checklist was rendered initially and after the updates to attribute values.

Ordered List AttributesOrdered List AttributesOrdered List Attributes

As you may see, the counting order remains to be reversed regardless that we now have set the worth of reversed to false. The rationale 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 strongly recommended that you just set the worth of such attributes to both an empty string or attribute names if you need them to be true. The one option to stop the reversal from taking place is to take away the attribute fully utilizing the removeAttribute() methodology.

1
pop_countries.removeAttribute("reversed");

Add, Take away, Change or Toggle Factor Courses

You in all probability already know in regards to the class attribute that we are able to use with completely different HTML parts to offer a space-separated checklist of courses. Courses play an essential function in number of parts for both making use of some styling or scripting.

Including, eradicating, changing and toggling courses of a component is definitely a quite common process in net growth. A component would possibly should be in lively or inactive state which you’ll be able to present by use of various courses.

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

The add() Technique

The classList property provides again a DOMTokenList of courses connected to the queried factor. You should use the add() methodology so as to add new tokens or class names to the checklist. It’s doable to move a number of class names to this methodology and any present token won’t 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 courses
7
message.classList.add("alert", "message");

The take away() Technique

You should use the take away() methodology if you wish to take away a number of courses from a component. No errors might be thrown if the category that you just wish to take away from a component is already absent from the factor’s class checklist.

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 courses
7
message.classList.take away("alert", "hidden");

The toggle() Technique

The toggle() methodology is helpful if you wish to take away a category whether it is within the DOMTokenList and add a category if it’s not 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 wish to toggle. The second parameter is a situation that you just wish to examine 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 use the return worth to substantiate if the category is current or absent after the operation.

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

The change() Technique

Some occasions, we wish to change an present class with a brand new one and do nothing if the outdated class is not already connected to the factor. The change() methodology works greatest on this case. It would return false if the substitute failed and true if the substitute was profitable.

Right here is a few code that listens to the clicking occasion on a button after which takes all paragraphs with a selected 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(process of planned_tasks) {
5
    process.classList.change("will-do", "completed");
6
  }
7
});

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

Ultimate Ideas

On this tutorial, we now have realized about native JavaScript strategies so as to add, replace or take away attributes to completely different parts in your webpage. It is extremely frequent for builders to control the courses related to a component. JavaScript permits you to do it way 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