为什么prepent()JavaScript方法不起作用?

发布于 2025-02-12 06:26:42 字数 1694 浏览 1 评论 0原文

课程后,我正在使用JavaScript进行DOM操纵。

我撰写了与课程中的人相同的代码,但它不起作用。代码应创建一个HTML元素并将其添加到DOM,但该元素未显示在页面中。此外,如果我打开了检查器工具,则元素在那里,但是像放置显示时一样亮了灰色:无 ...它是不可见的...

const header = document.querySelector('.header');
const message = document.createElement('div');
message.classList.add('cookie-message');
message.innerHTML =
  'We use cookies for improved functionality and analytics. <button class="btn btn--close-cookie">Got it!</button>';
header.prepend(message);
.header {
  padding: 3em;
  height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.cookie-message {
  display: flex;
  align-items: center;
  justify-content: space-evenly;
  width: 100%;
  background-color: white;
  color: #bbb;
  font-size: 1.5rem;
  font-weight: 400;
}
<!DOCTYPE html>
<html lang="en">
  <head>
  </head>
  <body>
    <header class="header">
    
    </header>
   </body>
   </html>

我正在使用Firefox作为浏览器,并且在MDN文档上看到了有关element.prepend(),它得到了Firefox的完全支持,但对我来说没有工作...

然后我尝试了Chrome并在Chrome上使用。

有人可以帮助我吗?我想念什么吗?

I'm practicing with DOM manipulation in JavaScript following a course.

I wriote the same code as the guy of the course but it doesn't work. The code should create an html element and add it to the DOM and it does, but the element is not showing in the page. Besides, if I open the inspector tool the element is there but is greyed out like when you put display:none ... it's invisible...
enter image description here

const header = document.querySelector('.header');
const message = document.createElement('div');
message.classList.add('cookie-message');
message.innerHTML =
  'We use cookies for improved functionality and analytics. <button class="btn btn--close-cookie">Got it!</button>';
header.prepend(message);
.header {
  padding: 3em;
  height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.cookie-message {
  display: flex;
  align-items: center;
  justify-content: space-evenly;
  width: 100%;
  background-color: white;
  color: #bbb;
  font-size: 1.5rem;
  font-weight: 400;
}
<!DOCTYPE html>
<html lang="en">
  <head>
  </head>
  <body>
    <header class="header">
    
    </header>
   </body>
   </html>

I am using FireFox as browser and I saw on MDN documentation about Element.prepend() that it is fully supported by FireFox but for me is not working...

Then I tried on Chrome and it works.

enter image description here

Someone can help me out? Am I missing something?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文