首页 > 解决方案 > JavaScript:如何在每个段落之后添加 iframe?

问题描述

我是 JavaScript 新手,期待专家的回答。

假设以下是我的内容-

<p> This is the first paragraph </p>
<p> This is the second paragraph </p>

而且,我想在每个段落之后添加一些代码块,并且代码如下 -

<p> This is the first paragraph </p>
<figure class="x">
  <iframe width="300" height="250" style="border:0; margin:0;" src="#">
  </iframe>
</figure>
<p> This is the second paragraph </p>
<figure class="x">
  <iframe width="300" height="250" style="border:0; margin:0;" src="#">
  </iframe>
</figure>

标签: javascript

解决方案


你可以试试这个 javascript 来开始。

// get all "p" tags
var elements = document.getElementsByTagName('p');

for (var i = 0; i < elements.length; i++) {
    // create figure
    const figure = document.createElement("figure");
    figure.className = "x";
    // create iframe
    const iframe = document.createElement("iframe");
    iframe.setAttribute("width", "300");
    iframe.setAttribute("height", "250");
    iframe.setAttribute("href", "#");
    iframe.style.border = 0;
    iframe.style.margin = 0;
    figure.appendChild(iframe);
    // append to "p" tag
    elements[i].parentNode.insertBefore(figure, elements[i].nextSibling);(figure);
}​

推荐阅读