I have HTML string which contains various elements. Consider following is the HTML string -
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>';
My requirement is to get tag before and after each img
tag. If tag before img
tag is p
tag, then replace it with <figure>
and closing </p>
with </figure>
.
I tried looping through img
tag and able to get image details perfectly.
How can replace elements before and after image.
$(this.content).find('img').each(function() {
console.log($(this).prev());
console.log($(this).attr('src'));
});
String I require -
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>';
Use replaceWith
( comments inline )
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());
Demo
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>
use replace
and regular expression
:
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 result=contentHTML.replace(/<p([^>]*?)>\\s*?<img([\\s\\S]*?)<\\/p>/g,'<figure$1><img$2</figure>'); console.log(result);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.