且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用内置 DOM 方法或原型从 HTML 字符串创建新的 DOM 元素

更新时间:2022-10-15 09:19:45

注意: 目前大多数浏览器都支持 HTML 元素,提供了更可靠的方式从字符串转换创建元素.有关详细信息,请参阅Mark Amery 在下方的回答.

对于较旧的浏览器和 node/jsdom:(在撰写本文时尚不支持 元素),请使用以下方法.这与库用来从 HTML 字符串中获取 DOM 元素的操作相同(对 IE 进行一些额外的工作 以解决其 innerHTML 实现的错误):

function createElementFromHTML(htmlString) {var div = document.createElement('div');div.innerHTML = htmlString.trim();//将此改为 div.childNodes 以支持多个***节点返回 div.firstChild;}

请注意,与 HTML 模板不同,这 不会适用于某些不能合法地成为

子元素的元素,例如 ;s.

如果您已经在使用库,我建议您坚持使用库认可的从 HTML 字符串创建元素的方法:

I have an HTML string representing an element: '<li>text</li>'. I'd like to append it to an element in the DOM (a ul in my case). How can I do this with Prototype or with DOM methods?

(I know i could do this easily in jQuery, but unfortunately we're not using jQuery.)

Note: most current browsers support HTML <template> elements, which provide a more reliable way of turning creating elements from strings. See Mark Amery's answer below for details.

For older browsers, and node/jsdom: (which doesn't yet support <template> elements at the time of writing), use the following method. It's the same thing the libraries use to do to get DOM elements from an HTML string (with some extra work for IE to work around bugs with its implementation of innerHTML):

function createElementFromHTML(htmlString) {
  var div = document.createElement('div');
  div.innerHTML = htmlString.trim();

  // Change this to div.childNodes to support multiple top-level nodes
  return div.firstChild; 
}

Note that unlike HTML templates this won't work for some elements that cannot legally be children of a <div>, such as <td>s.

If you're already using a library, I would recommend you stick to the library-approved method of creating elements from HTML strings:

登录 关闭
扫码关注1秒登录
使用内置 DOM 方法或原型从 HTML 字符串创建新的 DOM 元素
发送“验证码”获取 | 15天全站免登陆