Добавить текст из html в другой раздел - PullRequest
0 голосов
/ 15 января 2020

Я пытаюсь перебрать этот html и получить заголовки h4 и первое предложение каждого раздела, а затем добавить его в 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;

это html, я могу получить h4 для отображения, но они не отображаются под id = заголовки под заголовком h2.

<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>

1 Ответ

1 голос
/ 15 января 2020

Вы просто добавляете меню каждую итерацию l oop в тело по адресу:

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

Это говорит о том, что menu должно быть добавлено до firstChild в теле. И поскольку он находится внутри for l oop, он будет добавлен для каждого h4 элемента в вашем документе. Так что переместите его за пределы l oop.

. Вы должны выбрать пункт назначения и добавить туда меню. Как следующий

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