我有包含各种元素的 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/