Thursday , July 29 2021

How to call JavaScript code on multiple DIV elements without the ID attribute

Photo by Sergey Zolkin on Unsplash

Written by @js_tut (Twitter)

In this tutorial, we'll take a look at how to call JavaScript code on multiple DIV elements on the page, when the id attribute is missing (or when calling a single item is not allowed, for some reason.)

This happens more often than you may think. For example, you have an image gallery (or any other list of items) and you want to perform an action on each element but do not want to access each element individually.

Suppose you have a few arbitrary HTML DIV elements:

content 1

content 2

content 3

You can select these DIV elements, even if they do not have ID attributes. In fact, they share the same class name "image".

Let's look at some alternatives we have when it comes to selecting a collection of HTML elements. There are at least three ways to do it in JavaScript.

1. Use of document.getElementsByClassName

To select the items in question, you can use the document.getElementsByClassName function.

Returns an un-iterable collection of all elements.

In practice, it is just a list of elements, similar to (but not exactly like) a matrix.

to allow divs = document.getElementsByClassName("Image");

2. Use of document.getElementsByTagName

Same thing here, using only a different JavaScript function.

to allow divs = document.getElementsByTagName("Div");

3. Use of document.querySelectorAll

You can do the exact same thing with the document.querySelectorAll function.

to allow divs = document.querySelectorAll("Div");

What do these functions return?

console.log (div); // Let's give the results

Different types of objects. However, containing the selected items:

// getElementsByClassName (HTMLCollection)
// getElementsByTagName (HTMLCollection)

HTMLCollection (3) [div.image, div.image, div.image]
0: div.image
1: div.image
2: div.image
length: 3, __proto__: HTMLCollection
// querySelectorAll (NodeList)
NodeList (3) [div.image, div.image, div.image]
0: div.image
1: div.image
2: div.image
length: 3, __proto__: NodeList

The querySelectorAll returns to NodeList object.

getElementsByClassName / getElementsByTagName a HTMLCollection.

Everyone returns a list of all selected DIV elements That may be iterated.

You can take the div object, which will not contain the 3 elements, and iterate them one by one by calling Objects.entries:

Object.insertions(div).map((object) => {console.log (object)});

Alternatively you can for each one method of the formation object. But there are many different ways of doing the same thing in JavaScript. I usually use Object.entries e .map method. But it depends on you.

We attach an addEventListener method to each DIV in the collection:

Now that we've got the link to each HTML element in the list as a JavaScript object, let's do something with them:

/ * Add event listeners to all elements by hand * /
div[0].addEventListener ("click", function () {
console.log ("Hello" + this + "(" + this.innerHTML + ") from the event listener [0]");
/ * Here, "this" refers to the 1st div * /
div[1].addEventListener ("click", function () {
console.log ("Hello" + this + "(" + this.innerHTML + ") from the event listener [1]");
/ * Here, "this" refers to the 2nd div * /
div[2].addEventListener ("click", function () {
console.log ("Hello" + this + "(" + this.innerHTML + ") from the event listener [2]");
/ * Here, "this" refers to the 3rd div * /

Now every time you click on one of the DIVs, you get his own object is innerHTML printed on the console.

In some cases, you will want to do it individually. But this kind of defeats the whole purpose. We could not do it only by one? at the click attribute?

However, in most cases, you'll probably want to not only reduce the size of your code, but also scroll through all the existing elements in a collection one by one and run the same JavaScript code on all of them.

One way to do this is to use the method.

But the map the method works only on Array.

It will not work on one HTMLCollection. (Returned from all the examples above).

No problem. You can convert our collection into an array. And this can usually be done using the Object.entries method.

First of all, convert yours HTMLCollection using Object.entries (collection). So, since it is an "iterable", at this point it is now possible to use the .map method on it.

Using the .map method with Object.entries (collection)

/ * Explore the entire set of elements in an HTMLCollection
converting it first into an array using Object.entries * /
Object.entries (divs) .map ((object) => {
// Here, object = Array[index, object] (the object is the
// HTML element object). This means that the real element
// is stored in the object[1] not an object. Do everything you need to do
// with it here. In this case, we attach a click event:
object[1].addEventListener ("click", function () {
// Output innerHTML of the item you click on
console.log ("Hello" + This +
"(" + This.innerHTML + ") from the map ..." method);

Inside the cycle object[0] will refer to the index of the current article in the HTMLCollection. (In this case we have 3, because we started with 3

HTML elements.

Also, object[1] will actually indicate the JavaScript code object of that element

You can do whatever you want with it. Attacks mouse / blur events. Check their attributes. Take them off. Or anything else you would normally do with JavaScript objects, depending on your case.

The idea is that you write the JavaScript code once and you can apply it to a collection of HTML elements, without having to do it manually for each individual element.

This is pretty much all there is to do.

Source link

Leave a Reply

Your email address will not be published.