Search code examples
javascriptfor-loopgetelementsbytagname

Loop through h3 elements


everybody. I wanna make a for loop outputting my h3 elements. I could do it for one of them but to have them all, it doesn't output the content. And the a in the loop is for making inner links of my h3 in a long page.

function showH() {
  var x = document.getElementsByTagName("H3");

  let str = '<a href="">';
  for (var i =0; i < x.length; i++) {
    str += x[i] + "</a>";
  }
  document.getElementById("get").innerHTML = str;
}
<p id="get"></p>
<button onclick="showH()">click</button>

this code outputs:

[object HTMLHeadingElement][object HTMLHeadingElement][object HTMLHeadingElement][object HTMLHeadingElement]

Solution

  • x is an array of HTMLHeadingElements. To get the text, use .innerText.

    You also have some broken logic in your for loop. The first link will always work, but the links after will not be properly rendered because the start of the link tag is set to str and never added again.

    function showH() {
      var x = document.getElementsByTagName("H3");
      var str = "";
      for (var i = 0; i < x.length; i++) {
        str += '<a href="">' + x[i].innerText + "</a>";
      }
      document.getElementById("get").innerHTML = str;
    }
    <h3>Hello</h3>
    <h3>World</h3>
    <h3>!</h3>
    <p id="get"></p>
    <button onclick="showH()">click</button>