无法使用append()添加HTML块[已关闭]

bz4sfanl  于 2022-12-09  发布在  其他
关注(0)|答案(1)|浏览(137)

**已关闭。**此问题需要debugging details。当前不接受答案。

编辑问题以包括desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将有助于其他人回答问题。
19小时前关门了。
Improve this question
所以我想添加一个通知(const notification)到一个未排序的列表(notification-menu),但是控制台不断返回append不是一个有效的函数
`

const notificationMenu = document.getElementsByClassName("notification-menu")
/*const notificationItem = document.getElementsByClassName("notification")*/
const notification = `        <li class="notification">        <!--NOTIFICATION-->
            <article class="notification-item">
                <p class="notification-text">Gematched met:</p>
                <a href="andermans-profiel.html" class="notification-button">Bezoek profiel</a>
            </article>
            <article class="notification-informatie">
                <img src=../assets/img/rayan.png class="notification-item-foto"></src>
                <article class="notification-naam-leeftijd">
                    <p class="notification-foto-naam">Ryan</p>
                    <p class="notification-foto-leeftijd">42</p>
                </article>
            </article>
            <button class="notification-delete" onclick="this.parentNode.parentNode.removeChild(this.parentNode);">
                <i><img src=../assets/img/delete.webp class="kruis" height="30" width="30"></i>
            </button>
        </li>`

function nieuweNotification(){
    notificationMenu.append(notification)
}

nieuweNotification()

`
已尝试appendChild,但没有效果

zbdgwd5y

zbdgwd5y1#

  • 由于您通过类名获得了元素,因此notificationMenu是一个数组
  • notification是不是元素类型的字符串,您可以将其添加到notificationMenu的innerHTML中
const notificationMenu = document.getElementsByClassName("notification-menu")
 const notification = `        <li class="notification">        <!--NOTIFICATION-->
     <article class="notification-item">
         <p class="notification-text">Gematched met:</p>
         <a href="andermans-profiel.html" class="notification-button">Bezoek profiel</a>
     </article>
     <article class="notification-informatie">
         <img src=../assets/img/rayan.png class="notification-item-foto"></src>
         <article class="notification-naam-leeftijd">
             <p class="notification-foto-naam">Ryan</p>
             <p class="notification-foto-leeftijd">42</p>
         </article>
     </article>
     <button class="notification-delete" onclick="this.parentNode.parentNode.removeChild(this.parentNode);">
         <i><img src=../assets/img/delete.webp class="kruis" height="30" width="30"></i>
     </button>
 </li>`
 function nieuweNotification() {
   notificationMenu[0].innerHTML = notification;
 }
  • 如果要使用appendChild,则需要通过document创建Elements。createElement
function nieuweNotification() {
   var list = document.createElement("li");
   notificationMenu[0].appendChild(list);
 }

相关问题