Home >Web Front-end >JS Tutorial >How Can I Create DOM Elements from HTML Strings Without jQuery?
Creating DOM Elements from HTML Strings
While jQuery offers a convenient mechanism for creating DOM elements from HTML strings, this functionality can also be achieved using built-in DOM methods or through the Prototype library.
DOM Methods
For older browsers, as well as node/jsdom (which at the time of writing did not support HTML elements), the following method can be employed:
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; }
It is important to note that this method will not work for some elements that cannot be legally children of a
Prototype Library
Alternatively, the Prototype library provides a built-in method for creating elements from HTML strings through its update() method. Here's an example:
var element = $(document.createElement('li')).update('<li>text</li>');
Use Cases
Both built-in DOM methods and the Prototype library offer reliable ways of creating DOM elements from HTML strings, particularly for older browsers or in scenarios where jQuery is not utilized. These methods provide a flexible and robust approach for dynamically generating DOM content based on HTML markup.
The above is the detailed content of How Can I Create DOM Elements from HTML Strings Without jQuery?. For more information, please follow other related articles on the PHP Chinese website!