以下是我的HTML:
<html>
<head></head>
<body>
<section>
<div class="should_be_replaced">something</div>
</section>
</body>
</html>此外,我还有一个变量,它包含一些HTML标记:
var str = "<b>title</b><p>sth <span>sss</span></p>";现在,我想用div.should_be_replaced元素替换上面变量的内容。我怎么能这么做?
这是预期结果:
<html>
<head></head>
<body>
<section>
<b>title</b><p>sth <span>sss</span></p>
</section>
</body>
</html>发布于 2017-03-25 10:51:00
您可以使用jQuery的replaceWith
$('.should_be_replaced').replaceWith(str);
var str = "<b>title</b><p>sth <span>sss</span></p>";
$('.should_be_replaced').replaceWith(str);<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head></head>
<body>
<section>
<div class="should_be_replaced">something</div>
</section>
</body>
</html>
无jQuery
document.querySelector('.should_be_replaced').outerHTML = str;
var str = "<b>title</b><p>sth <span>sss</span></p>";
document.querySelector('.should_be_replaced').outerHTML = str;<html>
<head></head>
<body>
<section>
<div class="should_be_replaced">something</div>
</section>
</body>
</html>
发布于 2017-03-25 10:49:16
如果您有jQuery,您可以这样做:
var str = "<b>title</b><p>sth <span>sss</span></p>";
$(".should_be_replaced").parent().html(str);或者没有jQuery
document.getElementsByClassName('should_be_replaced')[0].parentNode.innerHTML = str发布于 2017-03-25 11:58:53
您可以使用直接html方法更改内容。
var str = "<b>title</b><p>sth <span>sss</span></p>";
jQuery("section").html(str);http://jsfiddle.net/dmxk59gg/
https://stackoverflow.com/questions/43015429
复制相似问题