2016-08-23 147 views
0
html = "<p>title</p><div><ul class='www'></ul>something</div>"; 
$html = $(html); 
$html.filter('p').replaceWith('<h2>' + $html.filter('p').html() + '</h2>'); //not working 
container = $('<div></div>'); 
html = container.html($html)[0].innerHTML; //trying to output "<h2>title</h2><div><ul class='www'></ul>something</div>" 

在非DOM环境中,我试图修改一个HTML字符串,替换其中的一个成员。 jQuery的replaceWith不起作用,因为它是针对DOM的。我该怎么做呢?替换jQuery非DOM对象中的元素之一

回答

0

看看这个例子。首先,我删除B,然后将其前置到A.之后,我插入一个新的C.您可以用A,B和C替换所有内容。

重要的是,您删除和附加/添加它manuallay :)

a = $('#a'); 
 
b = $('#b'); 
 
c = $('<span>').attr('id', 'c').text('C'); 
 

 
b.remove(); 
 
a.prepend(b); 
 
a.append(c);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="parent"> 
 
    <span id="a">A</span> 
 
    <span id="b">B</span> 
 
</div>

0

虽然元素被替换,$html不更新p是的根$html可变

html = "<p>title</p><div><ul class='www'></ul>something</div>"; 
 
$container = $('<div></div>'); 
 
$container.html(html); 
 
$container.find('p').replaceWith(function(idx, html) { 
 
    return '<h2>' + html + '</h2>' 
 
}) 
 
html = $container[0].innerHTML; 
 
console.log(html)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>