Search code examples
javascripthtmldomappendappendchild

Append text from html into different section


Im trying to iterate through this html and get the h4 headers and the first sentence of each section and then append it into a div.

function sumary () {
let headings = document.getElementsByTagName("h4"); // Get H4s
let newsText = document.getElementsByClassName("newsarticle").firstChild; // gets first "P" from 
each "class="Newsarticle"
let menu = document.createElement("div");          // Create DIV
let menuUList = document.createElement("ul");     // Create UL
menu.appendChild(menuUList);                      // Append UL to DIV
for (let i = 0; i < headings.length; i++) {
    let menuUListItem = document.createElement("li"); // Create an LI for each H4 text
    menuUList.appendChild(menuUListItem); // Append the LI to the UL
    let menuUListItemLink = document.createElement("a"); // Create a A for each LI
    menuUListItem.appendChild(menuUListItemLink); // Append the A to the LI
    let linkText = headings[i].childNodes[0].nodeValue; // Find the text content of each H4
    let menuText = document.createTextNode(linkText); // Create a text node out of each H4 text
    menuUListItemLink.appendChild(menuText); // Append the text node to the A element
    document.body.insertBefore(menu, document.body.firstChild); //Insert into HTML
}

window.onload = makeNavMenu;

this is the html, i can get the h4 to display but they dont display under the id= Headlines under the h2 heading.

<body>
<div id="wrappermain">
<h1>........</h1>

    <section id="headlines">
        <h2>.....</h2>  
    </section>

    <section id="news">
        <h3>......</h3>
        <article class="newsarticle">
            <h4>........</h4>
            <p>........</p>
            <p></p>
        </article>
        <article class="newsarticle">
            <h4>.......</h4>
            <p>.....</p>
        </article>
        <article class="newsarticle">
            <h4>.....</h4>
            <p>.......</p>  
        </article>
        <article class="newsarticle">
            <h4>....</h4>
            <p>.......</p>  
            <p>.......</p>  
        </article>
    </section>
</div>


Solution

  • You are simply appending the menu every iteration of the loop into the body at:

    document.body.insertBefore(menu, document.body.firstChild); //Insert into HTML
    

    This says that menu should be added before the firstChild in the body. And because it is inside for loop it will added for every h4 element in your document. So move it outside of the loop.

    You should select your destination and add the menu there. Like the following

    const target = document.querySelector('#headlines'); // Select <section id="headlines">.
    target.insertAdjecentElement('beforeend', menu); // Adds menu to the end in headlines.