【问题标题】:Append text from html into different section将文本从 html 附加到不同的部分
【发布时间】:2020-05-01 16:38:01
【问题描述】:

我试图遍历这个 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 显示,但它们不会显示在 h2 标题下的 id= Headlines 下。

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

【问题讨论】:

    标签: javascript html dom append appendchild


    【解决方案1】:

    您只是在循环的每次迭代中将菜单附加到正文中:

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

    这表示menu 应该添加到正文中的firstChild 之前。因为它在for 循环内,所以它会为文档中的每个h4 元素添加。所以把它移到循环之外。

    您应该选择目的地并在那里添加菜单。像下面这样

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-07
      • 2012-10-01
      • 2021-05-23
      • 2014-09-03
      相关资源
      最近更新 更多