这是我的 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>
你可以使用 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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句