3

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.

kind user
  • 40,029
  • 7
  • 67
  • 77
emha
  • 71
  • 1
  • 8
  • Rare you ever need to query the DOM in React. You typically have the source data that is used to fill those elements in your component already – charlietfl Oct 26 '20 at 23:56
  • in this case I need to create the html from a markdown file. Couldn't think of a different solution. – emha Oct 27 '20 at 09:48

2 Answers2

5

You could use Array.from.

For example returning the classes of each elem:

Array.from(document.getElementsByTagName('h2')).map(elem => elem.className)
Erik
  • 307
  • 1
  • 9
2

You can try something like this:

function App() {
    const [h2, setH2] = useState([]);

    const getH2 = () => {
        const elements = [];
        const el = document.getElementsByTagName('h2');
        for (const item of el) {
            elements.push(item.innerText);
        }
        setH2(elements);
    };
    return (
        <div>
            <h2>One</h2>
            <h2>Two</h2>
            <h2>Three</h2>
            <h2>Four</h2>

            <hr />
            <button onClick={getH2}>Get Innner Text</button>
            <hr />
            <ul>
                {h2.map((item, i) => (
                    <li key={i}>{item}</li>
                ))}
            </ul>
        </div>
    );
}

Live Demo: https://stackblitz.com/edit/react-vtb3fv

SakoBu
  • 3,972
  • 1
  • 16
  • 33