Search code examples
javascriptloopsinnerhtmlappendchild

How to loop through inner HTML


I need to loop through an article and get the heading and first paragraph and append it into another section id. I have this loop, it gets the h4 and p but how do i get the innerHTML? Thanks in advance.

function a(x) {
let result = document.getElementsByTagName(x);
for (let i = 0; i < result.length; i++) {
    console.log(result.length);
   }
   console.log(result);
}
window.onload = function(){
    a ("h4");
    a ("p");
}

Solution

  • Simply use the innerHTML property using the current index:

    for (let i = 0; i < result.length; i++) {
      console.log(result[i].innerHTML);
    }