HTML字符串使用jQuery替换标记

Neh*_*try 0 html javascript jquery

我有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>';
Run Code Online (Sandbox Code Playgroud)

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

我尝试循环img标记并能够完美地获取图像细节.

如何在图像前后替换元素.

$(this.content).find('img').each(function() {
    console.log($(this).prev());
    console.log($(this).attr('src'));
});
Run Code Online (Sandbox Code Playgroud)

字符串我要求 -

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>';
Run Code Online (Sandbox Code Playgroud)

gur*_*372 8

使用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());
Run Code Online (Sandbox Code Playgroud)

演示

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());
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Run Code Online (Sandbox Code Playgroud)