首页 > 解决方案 > 使用 javascript dom 在 HTML 中插入 Cite 元素

问题描述

我想在 HTML 中存在但为空的页脚标签中添加一个带有文本和 href 的引用元素(当前)

我正在使用此代码,但它不起作用。

let cite = document.createElement("cite");
cite.setAttribute("text","Information and photos from Wikipedia");
cite.setAttribute("href", "https://en.wikipedia.org/wiki/Bumblebee");
let ftr = document.getElementsByTagName('footer')[0];
ftr.innerHTML(cite);

我希望插入 dom 元素的 HTML 页面的代码是

<!DOCTYPE html>
<html lang="en">
<!-- DO NOT MODIFY THIS FILE OTHER THAN REFERENCING THE SCRIPT FILE -->

<head>
  <meta charset="UTF-8">
  <title>Assignment 5a</title>
  <link href="style.css" rel="stylesheet" />
</head>

<body>
  <header>
    <h1>Bumblebee</h1>
  </header>

  <main>
    <h2>General description</h2>

    <figure><img src="bee1.jpg" />
      <figcaption>A common bumblebee extending its tongue towards a Heuchera inflorescence.
      </figcaption>
    </figure>

    <p>Bumblebees  beast".</p>


    <h2>Distribution and habitat</h2>

    <figure><img src="bee2.jpg" />
      <figcaption>Cuckoo bumblebees have similar warning coloration to
        nest-making bumblebees.</figcaption>
    </figure>

    <p>Bumblebees t pollinators.</p>
  </main>
  <footer>

  </footer>
  <script type="text/javascript" src="script.js"></script>
</body>

</html>

请注意,我不能在 JS 文件和 document.write 中使用 HTML 标签

标签: javascript

解决方案


你很亲密。

此示例用于cite.textContent = 设置元素的内容,cite而不是设置名为“text”的属性。

它还用于ftr.appendChild(cite)cite元素添加到ftr页脚元素。这是因为innerHTML不采用 DOM 元素,而是采用 HTML 字符串。所以ftr.innerHTML = '<span>hello world</span'会起作用,但ftr.innerHTML = cite不会。

let cite = document.createElement("cite");
cite.textContent = "Information and photos from Wikipedia";
cite.setAttribute("href", "https://en.wikipedia.org/wiki/Bumblebee");
let ftr = document.getElementsByTagName('footer')[0];
ftr.appendChild(cite);
<!DOCTYPE html>
<html lang="en">
<!-- DO NOT MODIFY THIS FILE OTHER THAN REFERENCING THE SCRIPT FILE -->

<head>
  <meta charset="UTF-8">
  <title>Assignment 5a</title>
  <link href="style.css" rel="stylesheet" />
</head>

<body>
  <header>
    <h1>Bumblebee</h1>
  </header>

  <main>
    <h2>General description</h2>

    <figure><img src="bee1.jpg" />
      <figcaption>A common bumblebee extending its tongue towards a Heuchera inflorescence.
      </figcaption>
    </figure>

    <p>Bumblebees beast".</p>


    <h2>Distribution and habitat</h2>

    <figure><img src="bee2.jpg" />
      <figcaption>Cuckoo bumblebees have similar warning coloration to nest-making bumblebees.</figcaption>
    </figure>

    <p>Bumblebees t pollinators.</p>
  </main>
  <footer>

  </footer>
  <script type="text/javascript" src="script.js"></script>
</body>

</html>


推荐阅读