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.
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.
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.