将 HTML 元素添加到 DOM 而不是一串 HTML 文本
问题描述:
如何将元素添加到部分而不是纯字符串?
How can I add an element to a section rather than pure string?
我正在尝试使用 append
但它无法解析我的 HTML.
I am trying to use append
but that doesn’t parse my HTML.
也许还有更多我不知道的 AngularJS 方法.
Maybe there’s more AngularJS way of doing this I’m not aware of.
document.getElementsByClassName("left-menu")[0].append(
'<div class="adverts-container top30">' +
'<div class="advert-carousel">' +
'Message' +
'</div>' +
'</div>'
);
<section class="left-menu"></section>
答
ParentNode.append() 方法插入一组 Node 对象或 DOMString 而不是 htmlString.
ParentNode.append() method inserts a set of Node objects or DOMString not the htmlString.
我不知道角度方式,但您可以使用 insertAdjacentHTML()
在纯 JavaScript 中插入 htmlString.
I do not know the angular way but you can use insertAdjacentHTML()
to insert htmlString in pure JavaScript.
document.getElementsByClassName("left-menu")[0].insertAdjacentHTML( 'beforeend',
'<div class="adverts-container top30">' +
'<div class="advert-carousel">' +
'Message' +
'</div>' +
'</div>'
);
<section class="left-menu"></section>