Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>'. 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.)

like image 432
Omer Bokhari Avatar asked Jan 30 '09 01:01

Omer Bokhari


People also ask

Which one will create a new HTML element tag in DOM?

JavaScript CreateElementcreateElement() to create a new HTML element and attach it to the DOM tree. The document. createElement() accepts an HTML tag name and returns a new Node with the Element type.

Which of the method is used to create your elements in JavaScript DOM?

The getElementById Method The most common way to access an HTML element is to use the id of the element.


Video Answer


1 Answers

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:

  • Prototype has this feature built-into its update() method.
  • jQuery has it implemented in its jQuery(html) and jQuery.parseHTML methods.
like image 60
Crescent Fresh Avatar answered Sep 20 '22 13:09

Crescent Fresh