【问题标题】:Find and replace all elements inside div查找并替换 div 内的所有元素
【发布时间】:2015-03-10 21:15:02
【问题描述】:

我有一个带有奇怪标签figure的元素。

<div id="text"><div class="medium-insert-embeds" contenteditable="false">
    <figure>
        <div class="medium-insert-embed">
            <div style="left: 0px; width: 100%; height: 0px; position: relative; padding-bottom: 75.0019%;"><iframe src="https://www.youtube.com/embed/MYxsDlpMN10?wmode=transparent&amp;rel=0&amp;autohide=1&amp;showinfo=0&amp;enablejsapi=1" frameborder="0" allowfullscreen="true" webkitallowfullscreen="true" mozallowfullscreen="true" style="top: 0px; left: 0px; width: 100%; height: 100%; position: absolute;"></iframe></div>
        </div>
    </figure>
    <div class="medium-insert-embeds-overlay"></div>
</div><p class=""><br></p><p class=""><br></p><div class="medium-insert-embeds" contenteditable="false">
    <figure>
        <div class="medium-insert-embed">
            <div style="left: 0px; width: 100%; height: 0px; position: relative; padding-bottom: 75.0019%;"><iframe src="https://www.youtube.com/embed/MYxsDlpMN10?wmode=transparent&amp;rel=0&amp;autohide=1&amp;showinfo=0&amp;enablejsapi=1" frameborder="0" allowfullscreen="true" webkitallowfullscreen="true" mozallowfullscreen="true" style="top: 0px; left: 0px; width: 100%; height: 100%; position: absolute;"></iframe></div>
        </div>
    </figure>
    <div class="medium-insert-embeds-overlay"></div>
</div><p><br></p></div>

我想找到所有这些元素并使用 jquery 将它们替换为它们的内容。

var container = $('#text');
var htmlOfFirstFigure = container.find('figure').html(); //get html
container.find('figure').replaceWith(htmlOfFirstFigure); //replacing element

如果只有一个图形元素在 html 中,它可以正常工作。但是如何替换众多元素呢?

【问题讨论】:

    标签: jquery


    【解决方案1】:

    replaceWith 可以给定一个函数参数,它将在集合中的每个元素上调用该函数并将其替换为结果:

    container.find('figure').replaceWith(function() {
        return $(this).html();
    });
    

    【讨论】:

      猜你喜欢
      • 2021-12-12
      • 1970-01-01
      • 1970-01-01
      • 2011-10-29
      • 1970-01-01
      • 2023-01-12
      • 1970-01-01
      • 2011-12-15
      • 2020-11-24
      相关资源
      最近更新 更多