将 HTML 元素添加到 DOM 而不是一串 HTML 文本 [英] Append HTML element to the DOM instead of a string of HTML text

查看:20
本文介绍了将 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>

这篇关于将 HTML 元素添加到 DOM 而不是一串 HTML 文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆