2016-08-23 46 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>