简体   繁体   English

如何将一个 HTML 元素插入另一个元素?

[英]How to insert one HTML element inside another?

There is a function:有一个function:

function mapBuilder(container, props) {
    var map = document.createElement('app-map');
    document.getElementById(container).innerHTML += map;
    return map;
}

Using is:使用的是:

  <div id="map"></div>
     <script src="map.js"></script>
        <script>
            mapBuilder('map', {sidebar: true});
        </script>

Why after execution line document.getElementById(container).innerHTML += map;为什么执行行后document.getElementById(container).innerHTML += map; I get the text [object HTMLElement] on the page instead of real HTML element?我在页面上得到文本[object HTMLElement]而不是真正的 HTML 元素?

map is a node element, not a string with HTML, so in this case you should use appendChild() map 是一个节点元素,而不是带有 HTML 的字符串,所以在这种情况下你应该使用appendChild()

document.getElementById(container).appendChild(map);

Check https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML .检查https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML This method inserts some HTML to a certain place in DOM.此方法将一些 HTML 插入到 DOM 中的某个位置。 You can also use.appendChild().你也可以使用.appendChild()。

If you want to append, use appendChild .如果要 append,请使用appendChild If you want to place before a child element, use ChildNode.before If you want to place after a child element, use ChildNode.after如果要放置在子元素之前,请使用ChildNode.before如果要放置在子元素之后,请使用ChildNode.after

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM