Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to map through document.getgetElementsByTagName in reactjs [duplicate]

I am trying to map through the resulting Object when I run document.getElementsByTagName. I realize I can't map through objects, only arrays, but I cannot figure out how to convert it to an object to make it iterable.

my code looks like this:

const [h2, setH2] = useState([]);

const getH2 = () => {
setH2(document.getElementsByTagName("h2"));
console.log(h2)
  }

which gives me the following result: console log

trying to map through h2 returns the error:

TypeError: h2.map is not a function

I've also tried h2.HTMLCollection.map() but it throws the same error.

How can I map thorugh the result of docuemnt.getElementsByTagName ? I tried converting the object to an array but unsuccessfully so far.

like image 467
emha Avatar asked Nov 14 '25 17:11

emha


1 Answers

You could use Array.from.

For example returning the classes of each elem:

Array.from(document.getElementsByTagName('h2')).map(elem => elem.className)
like image 110
Erik Avatar answered Nov 17 '25 09:11

Erik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!