javascript - 使用 jQuery 替换 HTML 字符串标签

标签 javascript jquery html

我有包含各种元素的 HTML 字符串。 考虑以下是 HTML 字符串 -

var contentHTML = '<p>Some random string</p><p><img src="xyz.jpg" style="width: 100%;"><span some style></span></p><p><span style="font-size: 16.8px;"><b>Ingredients</b></span></p><p>Again some string</p><p><img src="xyz.jpg" style="width: 100%;"></p>';

我的要求是在每个 img 之前和之后获取标签标签。如果标记在img之前标签是p标签,然后将其替换为 <figure>并关闭</p></figure> .

我尝试循环img标签并能够完美获取图像细节。

如何替换图像前后的元素。

$(this.content).find('img').each(function() {
    console.log($(this).prev());
    console.log($(this).attr('src'));
});

我需要的字符串 -

var contentHTML = '<p>Some random string</p><figure><img src="xyz.jpg" style="width: 100%;"><span some style></span></figure><p><span style="font-size: 16.8px;"><b>Ingredients</b></span></p><p>Again some string</p><figure><img src="xyz.jpg" style="width: 100%;"></figure>';

最佳答案

使用replaceWith(内联注释)

var $contentHTML = $( "<div>" + contentHTML + "</div>");

$contentHTML.find( "img" ).each( function(){ //iterate all img elements
  var $parentP = $(this).parent(); //get the parent element
  if ( $parentP[0].nodeName == "P" ) //check if the parent Element is P
  {
     var innerHTML = $parentP.html(); //save the innerHTML value
     $parentP.replaceWith( "<figure>" + innerHTML + "</figure>" ); //replace with figure and retain saved html value
  }
});
console.log($contentHTML.html());

演示

var contentHTML = `<p>Some random string</p><p><img src="xyz.jpg" style="width: 100%;"><span some style></span></p><p><span style="font-size: 16.8px;"><b>Ingredients</b></span></p><p>Again some string</p><p><img src="xyz.jpg" style="width: 100%;"></p>`;

var $contentHTML = $( "<div>" + contentHTML + "</div>");

$contentHTML.find( "img" ).each( function(){
  var $parentP = $(this).parent();
  if ( $parentP[0].nodeName == "P" )
  {
     var innerHTML = $parentP.html();
     $parentP.replaceWith( "<figure>" + innerHTML + "</figure>" );
  }
});
console.log($contentHTML.html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

关于javascript - 使用 jQuery 替换 HTML 字符串标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48825941/

相关文章:

javascript - Ajax 表单 - 仍然无法使其与验证一起使用

javascript - 隐藏并显示 iframe 元素后,iframe 滚动条不会在 chrome 中显示

jQuery:选择不是某个类的后代的所有元素

jquery - 如何在不刷新整个页面的情况下提交表单

javascript - 如何定位子菜单元素(xpath、className 或 css 定位器)

javascript - 数组中的对象 : Unexpected String

javascript - 在页面上显示 JSON?

javascript - webpack 的 package.json 解析错误

jquery - 如何在预制的 jquery 画廊中创建一个看起来像照片的链接?

html - Buffalo v0.11.0 与 flash 和 application.html 有问题吗?