How to get all the html elements found by document.getElementsByClassName()

In the DevTools, I want to print or copy to the clipboard all the elements of a certain class name. I am interested in the HTML code itself, not in JS objects/code. I tried:

document.getElementsByClassName("some_class_name")      //returns some kind of object
document.getElementsByClassName("some_class_name")[0]  //gives HTML but only of the first found element, rather than all found elements.

I ultimately want to do something like:

copy(document.getElementsByClassName("some_class_name"));    //place found elements in the clipboard

So that I can paste it in my code editor to further understand it.

Any help would be greatly appreciated!

If I recall correctly, document.getElementsByClassName returns an array. An array is a data structure that has zero-based indexing. Like here’s an example.

var myNumArray = [1,2,3,4]; 

1 is at index zero and here’s how we can get it.

const firstNumber = myNumArray [0]; 

Hope this helps you. :slight_smile:

@a2937
hey thanks for the help. I am not only interested in the first element (index element [0]) but all of the found elements.

The end result I am expecting is for my clipboard to have the following:

<div class="red_car">car1</div>
<div class="red_car">car2</div>
<div class="red_car">car3</div>
<div class="red_car">car4</div>

Here is this Clipboard API and the relevant method

  navigator.clipboard.write(data).then(
    () => {
      /* success */
    },
    () => {
      /* failure */
    },
  );

This is how to get HTML of the elements.

const d = document.getElementById("d");
console.log(d.outerHTML);

If there’s anything else you need help with , let me know.

Have a nice day. :slight_smile:

2 Likes

Both querySelectorAll and getElementsByClassName returns a “collection”, respectively a NodeList or an HTMLCollection.

If you think about it that is really the only sensible thing. It has to contain multiple elements so it must be inside an object/array-like data structure. You can loop it to get to each of the elements.

document.querySelectorAll('.test').forEach((ele) => console.log(ele)); // elements

document.querySelectorAll('.test').forEach((ele) => console.log(ele.innerHTML)); // HTML content of the elements

Edit: forEach is on the NodeList structure, it doesn’t work with getElementsByClassName unless you transform it to an actual array first.


2 Likes

Thank you so much for helping, both of you. I understand much better now

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.