Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
415 views
in Technique[技术] by (71.8m points)

javascript - 使用内置DOM方法或原型从HTML字符串创建新的DOM元素(Creating a new DOM element from an HTML string using built-in DOM methods or Prototype)

I have an HTML string representing an element: '<li>text</li>' .

(我有一个表示元素的HTML字符串: '<li>text</li>' 。)

I'd like to append it to an element in the DOM (a ul in my case).

(我想将其附加到DOM中的元素(以我的情况为ul )。)

How can I do this with Prototype or with DOM methods?

(如何使用Prototype或DOM方法做到这一点?)

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

((我知道我可以在jQuery中轻松完成此操作,但不幸的是,我们没有使用jQuery。))

  ask by Omer Bokhari translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Note: most current browsers support HTML <template> elements, which provide a more reliable way of turning creating elements from strings.

(注意:当前大多数浏览器都支持HTML <template>元素,该元素提供了一种更可靠的方式来转换从字符串创建元素的方式。)

See Mark Amery's answer below for details .

(有关详细信息,请参见下面的Mark Amery的答案 。)

For older browsers, and node/jsdom : (which doesn't yet support <template> elements at the time of writing), use the following method.

(对于较旧的浏览器和node / jsdom :(在撰写本文时尚不支持<template>元素),请使用以下方法。)

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 ):

(库用于从HTML字符串中获取DOM元素的方法是相同的( IE还要做一些额外的工作来解决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.

(请注意,与HTML模板不同,这不适用于某些不能合法地成为<div>子元素的元素,例如<td> 。)

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

(如果您已经在使用库,建议您坚持使用库批准的从HTML字符串创建元素的方法:)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...