仅使用纯 JavaScript(无 jQuery)将元素添加到给定纯文本 HTML 的 DOM [英] Add elements to the DOM given plain text HTML using only pure JavaScript (no jQuery)

查看:28
本文介绍了仅使用纯 JavaScript(无 jQuery)将元素添加到给定纯文本 HTML 的 DOM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要能够在给定 HTML 原始文本字符串的情况下向页面添加元素,包括任意数量的标签、属性等.理想情况下,我希望能够对任何格式正确的任意字符串执行类似操作html;

I need to be able to add elements to a page given a raw text string of HTML, including any number of tags, attributes etc. Ideally I would like to be able to do something like with any arbitrary string of well-formed html;

 var theElement = document.createElement("<h1 id='title'>Some Title</h1><span style="display:inline-block; width=100px;">Some arbitrary text</span>");

document.getElementById("body").appendChild(theElement);

显然这行不通,我正在寻找实现相同结果的好方法.如果可能,我想避免解析 HTML.我可以使用的工具受到严格限制,没有 jQuery 或外部包含,并且必须跨浏览器并向后兼容到 IE6.任何帮助都是巨大的.

Obviously that doesn't work, I'm looking for good ways to achieve the same result. I'd like to avoid parsing the HTML if possible. I'm severely restricted on the tools I can use, no jQuery or outside includes and must be cross-browser and backward compatible down to IE6. Any help would be huge.

推荐答案

尝试分配给 匿名元素的 innerHTML 属性 并附加其每个 儿童.

Try assigning to the innerHTML property of an anonymous element and appending each of its children.

function appendHtml(el, str) {
  var div = document.createElement('div');
  div.innerHTML = str;
  while (div.children.length > 0) {
    el.appendChild(div.children[0]);
  }
}
var html = '<h1 id="title">Some Title</h1><span style="display:inline-block; width=100px;">Some arbitrary text</span>';
appendHtml(document.body, html); // "body" has two more children - h1 and span.

这篇关于仅使用纯 JavaScript(无 jQuery)将元素添加到给定纯文本 HTML 的 DOM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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