如何用另一个元素替换元素?

时间:2017-03-25 10:48:01

标签: javascript jquery html css

这是我的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>

5 个答案:

答案 0 :(得分:2)

如果你有jQuery,你可以这样做:

public class RootObject
        {
            public Dictionary<string,Routes> routes { get; set; }
            public Orders orders { get; set; }
            public Vehicles vehicles { get; set; }
            public Depots depots { get; set; }
            public Drivers drivers { get; set; }
        }

或没有jQuery

var str = "<b>title</b><p>sth <span>sss</span></p>";
$(".should_be_replaced").parent().html(str);

答案 1 :(得分:1)

您可以使用jQuery&#39; replaceWith

$('.should_be_replaced').replaceWith(str);

&#13;
&#13;
var str = "<b>title</b><p>sth <span>sss</span></p>";
$('.should_be_replaced').replaceWith(str);
&#13;
<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>
&#13;
&#13;
&#13;

没有jQuery

document.querySelector('.should_be_replaced').outerHTML = str;

&#13;
&#13;
var str = "<b>title</b><p>sth <span>sss</span></p>";
document.querySelector('.should_be_replaced').outerHTML = str;
&#13;
<html>
    <head></head>
    <body>
        <section>
            <div class="should_be_replaced">something</div>
        </section>
    </body>
</html>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

您可以使用直接html方法更改内容。

var str = "<b>title</b><p>sth <span>sss</span></p>";
    jQuery("section").html(str);

http://jsfiddle.net/dmxk59gg/

答案 3 :(得分:0)

试试这个:

<html>
    <head></head>
    <body>
        <section>
            <div id="should_be_replaced" onclick="click()">something</div>
        </section>
     <script>
        function click() {
            var str = "<b>title</b><p>sth <span>sss</span></p>";
            document.getElementById("should_be_replaced").innerHTML = str;
        }
     </script>
    </body>
</html>

答案 4 :(得分:0)

你可以简单地通过jQuery来做。

var section = jQuery('section');
section.find('div').remove();
section.html(str);